一、对象冒充
1.
function ClassA(name){
this.name = name;
}
ClassA.prototype.getName = function(){
return this.name;
}
function ClassB(name){
this.method1 = ClassA;
this.method1(name);
delete ClassB.prototype.method1;
}
2.call
function ClassA(name){
this.name = name;
}
ClassA.prototype.getName = function(){
return this.name;
}
function ClassB(name){
ClassA.call(this,name);
}
可支持多继承
3.apply
function ClassA(name){
this.name = name;
}
ClassA.prototype.getName = function(){
return this.name;
}
function ClassB(name){
ClassA.apply(this,new Array(name));
}
二、原型链
function ClassA(){
}
ClassA.prototype.name = "张三";
ClassA.prototype.getName = function(){
return this.name;
}
ClassB.prototype = new ClassA();
ClassB.prototype.name = "王五";
不支持多继承
三、对象冒充+原型链
function ClassA(name){
this.name = name;
}
ClassA.prototype.getName = function(){
return this.name;
}
function ClassB(name){
ClassB.call(this,name);
}
ClassB.prototype = new ClassA();
ClassB.prototype.age = "10";