首页 > JavaScript > JavaScript Combination Constructor/Prototype Pattern
2010四月26

JavaScript Combination Constructor/Prototype Pattern

前面介绍过的Constructor pattern 和 Prototype pattern,都有着各自的优势和劣势。目前,创建自定义类型通用的方法是使用二者的混合模式。下面,我们就来使用混合模式重写前面的例子:

The constructor pattern defines instance properties, whereas the prototype pattern defines
methods and shared properties. With this approach, each instance ends up with its own copy of the
instance properties, but they all share references to methods, conserving memory. This pattern allows
arguments to be passed into the constructor as well, effectively combining the best parts of each pattern.

function Person(name, age, job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.friends = ["Shelby", "Court"];
}
                   
Person.prototype = {
    constructor: Person,
    sayName : function () {
        alert(this.name);
    }
};
                   
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
                   
person1.friends.push(“Van”);
                   
alert(person1.friends);    //"Shelby,Court,Van"
alert(person2.friends);    //"Shelby,Court"
alert(person1.friends === person2.friends);  //false
alert(person1.sayName === person2.sayName);  //true

现在,一切看起来都很完美不是吗?

The hybrid constructor/prototype pattern is the most widely used and accepted practice for defining
custom reference types in ECMAScript. Generally speaking, this is the default pattern to use for defining
reference types.

文章作者:simaopig
本文地址:http://www.xiaoxiaozi.com/2010/04/26/1752/
版权所有 © 转载时必须以链接形式注明作者和原始出处!

本文目前尚无任何评论.

发表评论

:wink: :twisted: :roll: :oops: :mrgreen: :lol: :idea: :evil: :cry: :arrow: :?: :-| :-x :-o :-P :-D :-? :) :( :!: 8-O 8)