gpt4 book ai didi

javascript - JavaScript 中这两个构造函数有什么区别?

转载 作者:行者123 更新时间:2023-12-02 17:32:22 25 4
gpt4 key购买 nike

在 MDN 上 page for Call有一个包含 3 个构造函数的示例:Product、Food 和 Toy

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

if (price < 0)
throw RangeError('Cannot create product "' + 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 = Object.create(Product.prototype);

我不能简单地这样做吗?

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

最佳答案

其中一个区别是语法。在我看来,第一个片段更好。

基本上是这样的:

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

以及稍后的内容

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

意味着他们共享相同的产品原型(prototype),这很好。但在您向我们展示的示例中,他们并没有真正利用 class 概念,该概念在 JavaScript 中并不真正存在,但在必须语言(例如 PHP)中很活跃。

您可以仅将功能或属性附加到玩具或食物上:

Food.prototype = Object.create(Product.prototype);
Food.prototype.eat = function(){ //Toy object can't call that function
alert('Om Nom Nom')
}

当然你也可以这样做:

function Food (name, price) {
var me = Product.call(this, name, price);
me.category = 'food';
me.eat = function(){
alert('Om Nom Nom');
};
return me;
}

但这会导致不必要的内存使用,并可能影响性能。

最后,使用instanceof将会是错误的。使用第二种方法,您将无法知道您的对象是否是产品:

//Method1
alert(foodObj instanceof Food); //true
alert(foodObj instanceof Product); //true

//Method2
alert(foodObj instanceof Food); //true
alert(foodObj instanceof Product); //false

Live example

关于javascript - JavaScript 中这两个构造函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22943313/

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