您的位置:首页 > 其它

创建对象

2016-05-19 10:47 246 查看

工厂模式


缺陷:无法知道对象类型


console.log("工厂模式");
//无法识别对象
function createPerson(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.sayName = function(){
console.log(this.name);
};
}
var person1 = createPerson("Nicholas", 29, "Software Engineer");
var person2 = createPerson("Greg", 27, "Doctor");

构造函数模式


缺点:方法不共享

new关键字会有以下4个步骤:

1)创建一个对象

2)将构造函数的作用域赋给新对象(因此this就指向该新对象)

3)执行构造函数中的代码

4)返回新对象


console.log("构造函数模式");
//方法不共享,都有自己的方法
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
console.log(this.name);
};
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
console.log(person1.constructor == Person); //true
console.log(person1 instanceof Object); //true
console.log(person1 instanceof Person); //true

原型模式


缺点:属性共享,属性不应该共享


console.log("原型模式");
//属性共享,属性不应该共享
function Person(){}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
console.log(this.name);
};
var person1 = new Person();
person1.sayName();  //Nicholas
var person2 = new Person();
person2.sayName();  //Nicholas
console.log(person1.sayName == person2.sayName);    //true

组合使用构造模式和原型模式


认可度最高的一种模式


console.log("组合使用构造模式和原型模式");
//认同度最高的构造模式
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelby", "Court"];
}
Person.prototype = {
// body...
constructor:Person,
sayName:function(){
console.log(this.name);
}
};
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
person1.friends.push("Van");
console.log(person1.friends);   //[ 'Shelby', 'Court', 'Van' ]
console.log(person2.friends);   //[ 'Shelby', 'Court' ]
console.log(person1.friends === person2.friends);   //false
console.log(person1.sayName === person2.sayName);   //true

动态原型模式

console.log("动态原型模式");
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
if (typeof this.sayName != "function"){
Person.prototype.sayName = function() {
// body...
console.log(this.name);
};
}
}
var friend = new Person("Nicholas", 29, "Software Engineer");
friend.sayName();

寄生构造函数模式

>代码上和工厂方式区别小,方式上区别
console.log("寄生构造函数模式");
function Person(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
console.log(this.name);
}
return o;
}
var friend = new Person("Nicholas", 29 ,"Software Enginner");
friend.sayName();

稳妥构造函数模式


没有this关键字


console.log("稳妥构造函数模式");
function Person(name, age, job){
var o = new Object();
o.sayName = function(){
console.log(name);
};
return o;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: