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
相关文章
相关标签/搜索