js面向对象-组合使用构造函数模式和原型模式(使用最广泛、认同度最高)
文章目录
组合使用构造函数模式和原型模式
构造函数模式用于定义实例属性
原型模式用于定义方法和共享的属性
优点:每个实例都有自己的实例属性的副本,但同时共享对方法的引用,最大限度的节省内存
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
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论