继承方式

2018-09-02  本文已影响0人  汤初景

原型链继承:

Child()的原型作为Parent()的实例来继承Parent()的方法属性

因为所有实例都继承原型方法属性,其中一个实例对原型属性值更改后,所有实例调用该属性的值全部更改

function Parent() {}  
Parent.prototype.parentSay = function() {  
    return 'i am parent';  
}  
function Child() {}  
Child.prototype.childSay = function() {  
    return 'i am child';  
}  
Child.prototype = new Parent();  
var par = new Parent();  
var kid = new Child();  
  
console.log(kid.parentSay());           //i am parent 

构造函数继承:

在子类的构造函数内部通过call或apply来调用父类构造函数

无法实现函数的复用

function People() {  
    this.name = ['zhangsan','lisi','wangwu'];  
}  
function Person() {  
    People.call(this);  
}  
var per1 = new Person();  
per1.name.push('zhanliu');  
console.log(per1.name);     //["zhangsan", "lisi", "wangwu", "zhanliu"]  
  
var per2 = new Person();  
console.log(per2.name);     //["zhangsan", "lisi", "wangwu"]  

组合继承:

将原型链继承和构造函数继承结合,最常用的继承模式

原型链继承共享的属性和方法,构造函数继承实例属性

function People(num) {  
    this.num = num;  
    this.name = ['zhangsan','lisi','wangwu'];  
}  
People.prototype.numCount = function() {  
    console.log(this.num);  
}  
function Person(num) {  
    People.call(this, num);  
}  
//继承方式  
Person.prototype = new People();  
Person.prototype.constructor = Person;  
  
var per1 = new Person(10);  
per1.name.push('zhaoliu');  
console.log(per1.name);     //["zhangsan", "lisi", "wangwu", "zhanliu"]  
per1.numCount();            //10  
  
var per2 = new Person(20);  
console.log(per2.name);     //["zhangsan", "lisi", "wangwu"]  
per2.numCount();            //20 
上一篇下一篇

猜你喜欢

热点阅读