gpt4 book ai didi

javascript - 返回原始类型有什么危险?

转载 作者:行者123 更新时间:2023-11-30 00:06:44 24 4
gpt4 key购买 nike

根据 @TobyHo

Number, String, Boolean, are all primitive types. If you return one of these types of values from a constructor, it would be ignored and the constructor would go back to its normal behavior of returning the this object.

  • 返回原始类型有什么危险(因为构造函数返回到它的正常行为)?

最佳答案

请注意,从技术上讲,任何函数都可以用作构造函数。

但为了突出功能,构想为构造函数,它们被称为大写字母:Animal,而不是动物。

通常,构造函数不返回任何东西ю他们的任务 - 写下你需要的一切,在这,它会自动产生

但是如果返回的显式调用仍然存在,那么它应用一个简单的规则:

  • 当返回调用对象时,将返回而不是返回这个。
  • 当你调用返回原始值时,它会被丢弃。

例如,对象返回:

function BigAnimal() {

this.name = "Mouse";

return { name: "Godzilla " }; // <-- return the object
}

alert( new BigAnimal().name ); // Godzilla, we got an object instead of this

这是一个行返回的例子:

function BigAnimal() {

this.name = "Mouse";

return "Godzilla"; // <-- return the primitive
}

alert( new BigAnimal().name ); // Mouse, received this (but Godzilla is gone)

作品的这个特性在新标准中注册了,但是很少使用。

关于javascript - 返回原始类型有什么危险?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38219443/

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