gpt4 book ai didi

Javascript-原型(prototype)继承

转载 作者:行者123 更新时间:2023-11-28 00:01:53 26 4
gpt4 key购买 nike

我不明白什么>让我们看一下 MDN 的示例:

function Product(name, price) {
this.name = name;
this.price = price;

if (price < 0) {
throw RangeError('Cannot create product ' +
this.name + ' with a negative price');
}

return this;
}

function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}

Food.prototype = Object.create(Product.prototype);
Food.prototype.constructor = Food; // Reset the constructor from Product to Food

为什么我必须写这部分:

Food.prototype = Object.create(Product.prototype);
Food.prototype.constructor = Food;

Product.call(this, name,price); 不是已经将该属性(Prototype)从 Product 复制到了 Food 吗?

最佳答案

这就是在 JavaScript 中对类进行伪经典实例化的方法。让我们首先看看当您只执行第一部分时会发生什么,但让我们添加一些内容以进行澄清:

function Product(name, price) {
this.name = name;
this.price = price;

if (price < 0) {
throw RangeError('Cannot create product ' +
this.name + ' with a negative price');
}

return this;
}

Product.prototype.declare = function () {
console.log('I like ' + this.name);
}

function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}

在控制台中运行此命令,然后运行 ​​console.dir(Product)console.dir(Food)。食品具有一些与产品相同的属性。但是,Food 无法访问 Product 原型(prototype)上的“declare”方法。因此,我们需要设置Food的原型(prototype)。在上面的代码之后在控制台中运行:

Food.prototype = Object.create(Product.prototype);

再次运行Foodconsole.dir。现在,Food 具有与 Product 具有相同属性/方法的原型(prototype)。然而,原型(prototype)的构造函数现在是“Product”。解决此问题的最后一步是设置 Food.prototype.constructor,因此 Food 的构造函数再次是 Food,但具有所有属性/产品的方法。

Food.prototype.constructor = Food;

通过 JavaScript 中的伪经典实例化实现完全继承是一个奇怪但合乎逻辑的过程。

关于Javascript-原型(prototype)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31726545/

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