gpt4 book ai didi

javascript - 原型(prototype)继承共享属性和方法

转载 作者:行者123 更新时间:2023-11-30 20:34:41 26 4
gpt4 key购买 nike

这是正确的原型(prototype)继承吗?这共享基类的属性和方法。 'class' 是一种语法糖。我想知道它是否与我在此代码中所做的完全相同。

    let Animal = function () {
this.eats = true;
}

Animal.prototype.run = function () {
console.log("Running");
}

let Lion = function () {
// Call the base class constructor
Animal.call(this);
this.roar = function () {
console.log("Roraring");
}
}

// Setup the prototype
Lion.prototype = Object.create(Animal.prototype);

// It is a good practice to set the constructor back to original
Lion.prototype.constructor = Lion;

var lion1 = new Lion();
lion1.run();
console.log(lion1.eats);

最佳答案

是的,我看到您使用的模式与 MDN 原型(prototype)继承页面中定义的模式完全相同。 class关键字是js中的一个语法糖,是正确的。使用“class”关键字可以完成的原型(prototype)绝对没有什么不能做的。

关于javascript - 原型(prototype)继承共享属性和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49963100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com