首页前端开发JavaScriptjavascript中的继承模式

javascript中的继承模式

时间2023-11-29 13:59:10发布访客分类JavaScript浏览630
导读:JavaScript继承是OOP编程的核心概念之一。其中,常见的继承模式有原型继承、构造函数继承、组合继承、寄生式继承等。原型继承是通过复制一个现有对象实例作为新对象的原型来实现继承。例如:function Parent( {this.n...

JavaScript继承是OOP编程的核心概念之一。其中,常见的继承模式有原型继承、构造函数继承、组合继承、寄生式继承等。

原型继承是通过复制一个现有对象实例作为新对象的原型来实现继承。例如:

function Parent() {
    this.name = 'parent';
}
Parent.prototype.getName = function() {
    return this.name;
}
    const child = Object.create(Parent.prototype);
    child.name = 'child';
    console.log(child.getName());
 // child

构造函数继承是通过在子类构造函数中调用父类构造函数来实现。例如:

function Parent() {
    this.name = 'parent';
}
Parent.prototype.getName = function() {
    return this.name;
}
function Child() {
    Parent.call(this);
    this.age = 18;
}
    const child = new Child();
    console.log(child.getName());
 // TypeError: child.getName is not a function

上例中,因为子类的原型没有指向父类的原型,所以无法访问父类原型上的方法。解决方案是使用组合继承。

组合继承是通过同时使用构造函数继承和原型继承来实现继承。例如:

function Parent() {
    this.name = 'parent';
}
Parent.prototype.getName = function() {
    return this.name;
}
function Child() {
    Parent.call(this);
    this.age = 18;
}
    Child.prototype = new Parent();
    Child.prototype.constructor = Child;
    const child = new Child();
    console.log(child.getName());
 // parent

寄生式继承是在一个已有的对象上创建一个新对象,可以通过附加方法等增强对象,然后返回这个新对象。例如:

function Parent() {
    this.name = 'parent';
}
Parent.prototype.getName = function() {
    return this.name;
}
function createChild() {
    const child = new Parent();
    child.age = 18;
    return child;
}
    const child = createChild();
    console.log(child.getName());
     // parent

总体而言,继承是JavaScript中一个非常重要的概念,通过不同的继承模式,我们可以实现不同的继承效果,使代码更加优雅、简洁和易于维护。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: javascript中的继承模式
本文地址: https://pptw.com/jishu/560522.html
css层叠最上面 css将图片限制大小

游客 回复需填写必要信息