如何用es5实现继承

extend (继承)

如何用 es5 实现继承

Father.prototype = {
    eat:function(){
        console.log(this.name+' eat something.')
    }
}

function Father(name) {
    this.name = name
    this.attr = "father's attr."
}
function Super() {
    this.constructor = Child
}
Super.prototype = Father.prototype
Child.prototype = new Super() // 继承父类的原型方法
function Child() {
    Father.apply(this, arguments) // 继承父类的属性
    this.attr = "child's attr"
}

测试

var child = new Child('Foo')

console.log(child,child.attr)

console.log(child instanceof Child, child instanceof Father)

child.eat()

console.log(child.newAttr)

Father.prototype.newAttr = '123'

console.log(child.newAttr)

console.log(Child.prototype.constructor === Child)

结果

Child { name: 'Foo', attr: 'child\'s attr' } 'child\'s attr'
true true
Foo eat something.
undefined
123
true

原文链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在线阅读 http://interview.poetries.top[http://interview.poetr...
    前端进阶之旅阅读 114,935评论 24 450
  • 正月十六,刚进入三月第3天,3天里却度过了3个雨夜,有时还夹着点雷声,白天则雨歇,时而艳阳时而多云,经春雨发酵后的...
    晋姐阅读 411评论 0 2
  • 经济学角度解释优质:1,品质稳定是优质。2,性价比相当才是优质。为了提高产品质量所要付出的边际成本,应该跟它得到的...
    Jessica_Zuo阅读 884评论 0 0
  • 在互联网刚兴起的时候,整个世界都炸开了,以前可望不可及的事物,现在都可以呈现在一个小小的屏幕上了。俗话说:足不出户...
    大泽天下阅读 291评论 1 1
  • 消逝也是一种美吧,不信你看那天边的晚霞。 人总是在幸福的时刻渴望永恒。窗外淅淅沥沥的小雨轻轻降临在树梢上、窗台上,...
    平静地平凡阅读 399评论 2 1