1 原型链继承
父类:
function Farther(){
this.name='hj';
this.sayName = function(){
console.log(this.name);
return null;
}
}
Farther.prototype.age = 40;
子类1:
function Son1(height){
this.height = height;
}
//这两句是重点
Son1.prototype = new Farther;
Son1.prototype.constructor = Son1;
//
var s1 = new Son1('178');
s1.sayName (); //hj
s1.age; //40
-----------------------------------------示例图片:------------------------------------------
![](https://img.haomeiwen.com/i11314343/2633375d54a3501c.png)
缺点:
不能给父类传参数;
父子构造函数的原型对象之间有共享问题;
2 构造函数继承
call/apply
父类:
function Farther(name){
this.name=name;
this.height = '178';
this.sayName = function(){
console.log(this.name);
return null;
}
}
Farther.prototype.age = 40;
子类:
function Son2 (name){
//这句是重点
Farther.call(this,name)
或者 Farther.apply(this,[name])
}
var s2 = new Son2('hj');
s2.sayName(); //hj
s2.height; //178
s2.age; //undefined
-----------------------------------------示例图片:------------------------------------------
![](https://img.haomeiwen.com/i11314343/74d2559b0829a441.png)
缺点:
可以传参,也不共享,但是,获取不到父类原型属性;
3 冒充对象继承
父类:
function Farther() {
this.name = 'hj';
this.height = '178';
}
Farther.prototype.age = 40;
子类:
function Son3(){
//这一块是重点
var tem = new Farther();
for(var key in tem){
if(tem.propertyIsEnumerable(key)){
this[key] = tem[key]
}
}
tem = null;
}
var s3 = new Son3();
s3.name; //hj
s3.height; //178
s3.age; //undefined
-----------------------------------------示例图片:------------------------------------------
![](https://img.haomeiwen.com/i11314343/78c5e78a131035f9.png)
缺点:
可以获取父类公有和私有属性,但是不能传参,也获取不到父类原型属性
4 原型式继承
父类:
function Farther() {
this.name = 'hj';
this.height = '178';
}
Farther.prototype.age = 40;
子类:
function Son4(){
}
//这句是重点
Son4.prototype = Farther.prototype;
var s4 = new Son4();
s4.name; //
s4.height; //
s4.age; //40
-----------------------------------------示例图片:------------------------------------------
![](https://img.haomeiwen.com/i11314343/eec134300a721647.png)
缺点:
成员共享问题;
只能继承原型属性;
5 原型和构造函数组合
既可以获取父类对象属性和原型属性
-----------------------------------------示例图片:------------------------------------------
![](https://img.haomeiwen.com/i11314343/18c784bbde41b0d4.png)
6 寄生组合继承
给Son5.prototype = _______________ 这部分加一个壳子即
Son5.prototype = Create(Farther.prototype); //Create is a function
function Create(tem){
function fn = {};
fn.prototype = new tem;
return new fn;
}
-----------------------------------------示例图片:------------------------------------------
![](https://img.haomeiwen.com/i11314343/6da3c983ff581337.png)
网友评论