js面向對象-組合使用構造函數模式和原型模式(使用最普遍、認同度最高)

組合使用構造函數模式和原型模式

構造函數模式用於定義實例屬性
原型模式用於定義方法和共享的屬性java

優勢:每一個實例都有本身的實例屬性的副本,但同時共享對方法的引用,最大限度的節省內存android

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("wwl1", 24, "java");
var person2 = new Person("wwl2", 25, "android");
person1.friends.push("Van");
alert(person1.friends); //"Shelby,Count,Van"
alert(person2.friends); //"Shelby,Count"
alert(person1.sayName === person2.sayName); //true
相關文章
相關標籤/搜索