一、工厂模式
function createPerson(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}
var person1 = createPerson("Nicholas", 29, "Software Engineer");
var person2 = createPerson("Greg", 27, "Doctor");
可以无数次调用上面这个函数,解决创建多个相似对象的问题,但是没有解决对象识别的问题(即怎样知道一个对象的类型)
二、构造函数模式
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
person1 和 person2 是两个不同的实例,但是它们的 constructor(构造函数)s属性都指向 Person。
alert(person1.constructor == Person); //true
alert(person2.constructor == Person); //true
三、原型模式
function Person() {}
Person.prototype.name = "Nicholas";
Person.prototype.age= 29;
Person.prototype.job= "Software Engineer";
Person.prototype.sayName= function(){
alert(this.name);
};
var person1 = new Person();
person1.sayName(); //"Nicholas"
var person2 = new Person();
person2.sayName(); //"Nicholas"
alert(person1.sayName == person2.sayName); //true
(1)验证构造函数 Person 的 prototype 是否是 person1 对象的原型
Person.prototype.isPrototypeOf(person1) //true
(2)Object.getPrototypeOf() 返回 [[Prototype]] 的值
Object.getPrototypeOf(person1)
(3)完全删除实例属性
delete person1.name;
(4)检测一个属性是否存在于实例中,若存在,返回 true
person1.hasOwnProperty("name")
(5)in 操作符
"name" in person1
在通过对象能够访问给定属性时返回 true,无论该属性存在于实例中还是原型中。
同时使用 hasOwnProperty() 和 in ,就可以确定该属性是存在于对象中,还是存在于原型中:
function hasPrototypeProperty(object, name) {
return !object.hasOwnProperty(name) && (name in object);
}
(6)for - in,返回的是所有能够通过对象访问的、可枚举的属性,无论是实例还是原型中的。
(7)Object.keys(对象) 返回对象上所有可枚举的实例属性
(8)Object.getOwnPropertyNames() 返回所有实例属性,无论是否可枚举
(9)使用下面的方式重设 constructor 属性会导致它的 [[Enumerable]]被设置为true,默认情况下,原生的 constructor 属性是不可枚举的。

可以使用 Object.defineProperty()

四、组合使用构造函数模式和原型模式

五、动态原型模式
function Person(name, age, job) {
//属性
this.name = name;
this.age = age;
this.job = job;
//方法
if (typeof this.sayName != "function") {
Person.prototype.sayName = function(){
alert(this.name);
};
}
}
六、寄生构造函数模式
七、稳妥构造函数模式
网友评论