修改和继承原型
先定义一个引用类型它包含一个属性
function SuperType(){
this.prototype = true;
}
//然后再给他写一个方法写到原型里面,方法是返回一个属性
SuperType.prototype.getSuperValue = function(){
return this.property
}
//在定义一个引用类型
function SubType(){
this.subproperty = false;
}
//继承了 SuperType, 注意此处相当于修改原型因为它将第二个类型的原型用第一个构造函数实例化了。
subType.prototype = new SuperType();
//这里又定义第二个类型的方法
SubType.prototype.getSubValue = function(){
return this.subproperty;
}
var instance = new SubType();
alert(instance.getSuperValue()); //true
//由于原型链被修改了后面实例化之后的东西也就被修改了
原型链最带的问题就是当定义的类中含有引用类型的值,比如数组,当通过原型链继承的时候,修改应用类型的值,无论创建多少个实例都会被修改。
//原型链的问题
function SuperType(){
this.colors = ['red', 'blue', 'green'];
}
function SubType (){
}
//继承 SuperType
SubType.prototype = new SuperType();
var instancel = new SubType();
instance1.colors.push('black');
alert(instance2.colors); //'red','blue','green','black'
var instance2 = new SubType();
alert(instance2.colors); //'red','blue','green','black'
网友评论