类的继承实现

function Parent(name) {
    this.parent = name;
}
Parent.prototype.say = function () {
    console.log(`Hello, ${this.parent}`)
}
function Child (name, parent) {
    // 将父类的构造函数绑定在子类上
    Parent.call(this, parent);
    this.child = name;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.say = function () {
    console.log(`Hello,${this.parent},I'm ${this.child}`);
}
// 将子类构造指向子类本身
Child.prototype.constructor = Child;
var parent = new Parent('testParent');
parent.say();
var child = new Child('testChild', 'testParent');
child.say();

参考资料

  1. www.cxymsg.com/guide/jsWri…

微信公众号“前端那些事儿”

发布了71 篇原创文章 · 获赞 43 · 访问量 79万+

猜你喜欢

转载自blog.csdn.net/cengjingcanghai123/article/details/104456664