gpt4 book ai didi

JavaScript 原型(prototype)和构造函数

转载 作者:行者123 更新时间:2023-12-02 16:07:37 26 4
gpt4 key购买 nike

为了学习 JavaScript,我有以下代码。

function Pizza(type, slices) {
this.type = type;
this.slices = slices;
}


Pizza.prototype.divvyUp = function () {
alert("The " + this.type + " pizza has been divvied up!");
};

var sausagePizza = new Pizza("sausage", 8);


sausagePizza.constructor.prototype.divvyUp();
sausagePizza.divvyUp();
if (sausagePizza.constructor.prototype.divvyUp === sausagePizza.divvyUp)
{
alert("yes they are equal");
}

问题是,当执行这两行代码时:

sausagePizza.constructor.prototype.divvyUp();
sausagePizza.divvyUp();

尽管它们旁边的 if 语句确认它们在类型和值方面是相等的。但第一行给我的结果是这样的:“未定义的披萨已被分割”,第二行结果给了我一个有点不同的结果,它是“香肠披萨已被分割”。我非常困惑,为什么这两个函数中的第一行不能读取 this.type 变量值,并在 divvyUp() 函数内的警报消息中抛出未定义的错误根据 if 语句相等。

最佳答案

两者之间的差异在于“this”在函数调用中的绑定(bind)方式。

左边的对象。函数调用前面是“this”绑定(bind)的对象。

sausagePizza.constructor.prototype.divvyUp();
//sausagePizza.constructor.prototype is left of the .divvyUp()
//so it is bound to this. However, the prototype object does not have
//a type property so it this.type returns undefined

但是,对于 sausagePizza 的情况,构造函数确实创建了这些属性。

sausagePizza.divvyUp()
//here sausage pizza is to left of .dizzyUp() and "this" is bound to it.

编辑:要理解 Javascript 中的原型(prototype),将所有内容都完整地阐明可能会有所帮助。首先函数是对象,这意味着它们具有属性。每个函数都是用一些基本属性创建的。其中之一是原型(prototype),它最初是一个空对象。

function Pizza(type, slices) {
this.type = type;
this.slices = slices;
}
console.log(Pizza.prototype) // prints {} an empty object

Pizza.prototype.divvyUp = function () {
alert("The " + this.type + " pizza has been divvied up!");
};
console.log(Pizza.prototype) // prints {divvyUp: [Function]}

现在,当我们在函数前面使用 new 运算符时,它会创建一个新的空对象,并设置对象 __proto__和构造函数属性,然后运行将“this”绑定(bind)为新对象的函数。

var sausagePizza = new Pizza("sausage", 8);
console.log(sausagePizza) // {type: "sausage", slices: 8}
//Objects in javascript can have hidden properties.
//If we unhide the relevant ones for this example
//sausagePizza really looks like this.

{
constructor: Pizza, //the function
__proto__: Pizza.prototype, //the object on the function
type: "sausage",
slices: 8
}

所以.运算符实际上是通过在左侧的对象中查找右侧的键来工作的(例如 . )。如果它在左侧的属性对象中找不到它要查找的键,那么它会查找 __proto__键的对象的。所以当你这样做时

sausagePizza.divvyUp()
//Javascript first looks into sausagePizza for divvyUp.
//It does not find it.
//then it looks for divvyUp in sausagePizza.__proto__
//it find divvyUp there and then () calls the function
//if javascript had not found divvyUp in sausagePizza.__proto__ then it would have
//looked into sausagePizza.__proto__.__proto__ if it existed, and so on

关于JavaScript 原型(prototype)和构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30563363/

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