-
Notifications
You must be signed in to change notification settings - Fork 25
Open
Description
/*
工厂模式
没有解决对象识别问题
*/
function createPerson(name, age, job) {
var o = {};
o.name = name;
o.age = age;
o.job = job;
o.sayName = function() {
console.log(this.name);
};
return o;
}
var p1 = createPerson('Lee', 22, 'Web Dev.');
/*
构造函数模式
每个方法都要在每个实例上重新创建一次
*/
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function() {
console.log(this.name);
};
}
var p1 = new Person('Lee', 22, 'Web Dev.');
/*
原型模式
原型上的属性是所有实例共享的,如果有引用类型会出问题(数组的操作)
不能向构造器传递初始化参数
*/
function Person() {}
Person.prototype.name = 'Lee';
Person.prototype.age = 22;
Person.prototype.job = 'Web Dev.';
Person.prototype.sayName = function() {
console.log(this.name);
};
var p1 = new Person();
/*
构造器/原型组合模式
*/
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.friends = ['you', 'me'];
}
Person.prototype = {
constructor: Person,
sayName: function() {
console.log(this.name);
}
};
/*
动态原型模式
*/
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
if (typeof this.sayName !== 'function') {
Person.prototype.sayName = function() {
console.log(this.name);
};
}
}
/*
寄生构造器模式
可以用于创建一个特殊的对象
*/
function Person(name, age, job) {
var o = {};
o.name = name;
o.age = age;
o.job = job;
o.sayName = function() {
console.log(this.name);
};
return o;
}
function SpecialArray() {
var values = [];
values.push.apply(values, arguments);
values.toPipedString = function() {
return this.join('|');
};
return values;
}
var colors = new SpecialArray('red', 'green', 'blue');
console.log(colors.toPipedString());
/*
持久构造器模式
不使用 new 进行调用
*/
function Person(name, age, job) {
//create the object to return
var o = {};
//optional: define private variables/functions here
//attach methods
o.sayName = function() {
console.log(name);
};
//return the object
return o;
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels