一、call、apply、bind对象冒充继承模式:
function Persion(){
this.name = '张三';
this.age = 20;
this.eat = function(){
alert(this.name+'在吃饭');
}
}
Persion.prototype.height = '170cm';
Persion.goto = function(){
alert('我是静态方法');
}
function Web(){
// Persion.call(this);
// Persion.apply(this);
Persion.bind(this)();
}
var w = new Web();
alert(w.name) // 张三
alert(w.height) // undefined
对象冒充继承模式的问题:call、apply、bind皆可继承构造函数Persion里面的属性和方法,但是原型链定义的属性和方法的无法继承二、原型链继承模式:原型链继承模式既可以继承对方的构造函数里的属性和方法,也可以继承对方原型链定义的属性和方法
function Persion(){
this.name = '张三';
this.age = 20;
this.eat = function(){
alert(this.name+'在吃饭');
}
}
Persion.prototype.height = '170cm';
Persion.goto = function(){
alert('我是静态方法');
}
function Web(){}
Web.prototype = new Persion();
var w = new Web();
alert(w.name) // 张三
alert(w.height) // 170cm
原型链继承的问题:实例化无法传参
function Persion(name, age){
this.name = name;
this.age = age;
this.eat = function(){
alert(this.name+'在吃饭');
}
}
function Web(){
}
Web.prototype = new Persion();
var w = new Web('张三', 20);
alert(w.name); // undefined
三、原型链+对象冒充的组合继承模式,既可以解决call等无法继承原型链属性方法的问题,又能解决原型链继承模式无法传参的问题
function Persion(name, age){
this.name = name;
this.age = age;
this.eat = function(){
alert(this.name+'在吃饭');
}
}
Persion.prototype.height = '170cm';
function Web(name,age){
Persion.call(this,name,age); // 对象冒充方法,解决传参问题
}
// 原型链赋值,解决无法继承原型链的属性和方法问题
Web.prototype = new Persion();
//或者
Web.prototype = Persion.prototype;
var w = new Web('李四',20);
alert(w.name); // 李四
alert(w.height); // 170cm
