美文网首页
三种常见继承

三种常见继承

作者: 沈墨空 | 来源:发表于2017-03-19 21:28 被阅读0次

1.原型继承

function A (){
    this.name = 'Jack';
}

function B (){
    this.type = 'type';
}

B.prototype = new A();

var b = new B();

console.log(b instanceof A);  // true

2.构造继承

function A (){
    this.name = 'Jack';
}

function B (){
    this.type = 'type';
    A.call(this);
}

var b = new B();

console.log(b instanceof A);  // false

对比

  • 构造函数继承的方法类似于复制,消耗内存
  • 构造函数继承的方法不能改变,而原型继承可以通过改变原型链改变

3.组合模式

  • 方法用原型继承 (公用)
  • 属性用构造继承 (私有)
function A (){
    this.name = 'Jack';
}
A.prototype.output = function(){
  console.log(this.name);  
}

function B (){
    this.type = 'type';
    A.call(this);
}

B.prototype = new A();

var b = new B();

b.output();  // 'Jack'

参考:http://web.jobbole.com/83319/

相关文章

网友评论

      本文标题:三种常见继承

      本文链接:https://www.haomeiwen.com/subject/llyvnttx.html