创建对象
构造函数模式
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");
new操作符的过程
- 创建一个新对象;
- 将构造函数的作用域赋给新对象(因此this就可以指向这个新对象);
- 执行构造函数里的代码;
- 返回新对象。
构造函数的问题
每个方法都要在每个实例中重新创建一遍。
原型模式
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();
原型模式的缺点
- 他忽略了为构造函数传递初始化参数的环节,结果所有实例在相同情况下都取得相同的属性值。
- 原型中所有属性被很多实例共享,这种共享对于函数非常适合,对于那些包含基本值的属性也说的过去,对于包含引用类型值的属性来说,问题就比较突出了。
组合使用构造函数模式和原型模式
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype = {
constructor: Person,
sayName: function() {
alert(this.name);
}
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
动态原型模式
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);
}
}
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
有其他OO语言经验的开发人员在看到独立的构造函数和原型时,可能会感到困惑。动态原型模式致力于解决这个问题。将所有信息封装在构造函数中。