gpt4 book ai didi

尚未设置值的 JavaScript 原型(prototype)属性

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

所以基本上我创建了一个虚拟主对象,然后通过原型(prototype)属性向其所有子对象添加一个属性。但当然,它是一个空的属性(property)。当使用 in 运算符进行条件检查以查看对象是否具有新属性时,结果是 false 并输出“Nothing There”。这是因为该特性还没有值(value)吗?

function Master(age, sex, location)
{
this.age = age;
this.sex = sex;
this.location = location;
}

var me = new Master(99, "Male", "Texas, USA");

Master.prototype.username;


if("username" in me)
{
document.write("The prototype put the property there.");
}
else
{
document.write("Nothing there.<br />");
}

最佳答案

这是因为还没有属性。仅仅尝试读取该属性并不会使其存在。 Master.prototype.username;window.foo 相同 - 它只是计算为 undefined,但没有其他 react 。如果您想为其设置一个值,请尝试:

Master.prototype.username = undefined;

或更好

Master.prototype.username = null;

nullundefined 之间的区别几乎在于,检查属性是否为 null 更容易;如果您向某些函数传递值 undefined 作为参数,它们会认为您根本没有传递任何值。

关于尚未设置值的 JavaScript 原型(prototype)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18325571/

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