jsは3つの一般的な方法のプロトタイプチェーンを継承します.
4049 ワード
1、
function SuperType() {
this.property = true;
}
SuperType.prototype.getSuperValue = function() {
return this.property;
}
function subType() {
this.property = false;
}
// SuperType
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function (){
return this.property;
}
var instance = new SubType();
console.log(instance.getSuperValue());//true
: , , ( )
, , 。 !
SuperType SubType ! prototype 。
, 。
2、
function SuperType(){
this.colors = ["red", "blue", "green"];
}
function SubType(){
// call() SuperType
SuperType.call(this);
}
var p1 = new SubType();
p1.colors.push("black");
alert(p.colors); //"red,blue,green,black"
var p2 = new SubType();
alert(p2.colors); //"red,blue,green;
! ,
。 call(this,"jack",15,"clerk") !
3、 ( , , )
function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function(){
alert(this.name)
};
function SubType(name, age){
//
SuperType.call(this, name);
this.age = age;
}
//
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;// constructor this , subtype,
SubType.prototype.sayAge = function(){
alert(this.age);
};
var instance1 = new SubType("Nicholas", 29);
instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black"
instance1.sayName(); //"Nicholas";
instance1.sayAge(); //29
: , !
call() , new , , 。
・