JavaScript原型使用要点
组合使用构造函数模式和原型模式
代码
//组合使用构造函数模式和原型模式
//构造函数
function Person(name, age, job) {
//实例属性
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelby", "Court"];
}
//原型
Person.prototype = {
constructor: Person,//设置constructor值
//原型方法
sayName: function() {
console.log(this.name);
}
}
//测试代码
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
person1.friends.push("Van");
console.log(person1.friends);
console.log(person2.friends);
console.log(person1.friends === person2.friends);
console.log(person1.sayName === person2.sayName);
结果
[ ‘Shelby’, ‘Court’, ‘Van’ ]
[ ‘Shelby’, ‘Court’ ]
false
true
寄生组合式继承
代码
//寄生组合式继承
function inheritPrototype(subType, superType) {
var prototype = Object(superType.prototype); //创建对象
prototype.constructor = subType; //增强对象
subType.prototype = prototype; //指定对象
}
function SuperType(name) {
this.name = name;
this.color = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function() {
console.log(this.name);
};
function SubType(name, age) {
SuperType.call(this, name);//在this作用域下调用SuperType构造函数
this.age = age;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function() {
console.log(this.age);
}
//测试代码
var sub = new SubType("Damian", 20);
sub.sayName();
sub.sayAge();
console.log(sub.color);
结果
Damian
20
[ ‘red’, ‘blue’, ‘green’ ]