gpt4 book ai didi

函数(构造函数)返回类型中的 Javascript 奇怪行为

转载 作者:行者123 更新时间:2023-11-30 17:35:04 25 4
gpt4 key购买 nike

假设我们有如下两个函数:

function a(){ this.x = 5; return {z:20};} 
function b(){ this.x = 5; return 30;}

现在如果你运行这些行,一切似乎都是合理的:

a(); //output : {z:20} 
b(); //output : 30;

但是如果您将它们作为对象构造函数运行:

new a() //output : Object {z:20} 
new b() //output : b {x:5}

我不明白 new 构造函数是否应该始终返回一个对象,为什么行为不同? JavaScript 会观察返回类型吗?如果返回类型是对象就直接返回,如果不是就返回初始化的实例?

我认为如果它是一个构造函数,那么它应该总是忽略返回类型并返回初始化的对象。我认为这种行为使 JavaScript 过于复杂。这里还有什么我不明白的吗?

最佳答案

I don't understand if the new constructor should always return an object, why is the behavior different? Does JavaScript watch the return type? If the return type is an object so returns it directly and if not it returns the initiated instance?

基本上是的。如果函数的返回值不是对象,则 new 运算符返回 this(新对象)(实际上是内部 [[Construct]] method 执行此操作)。

I think if it is a constructor, so it should ignore the return type always and returs the initiated object. I think this behavior makes JavaScript too complex. Is there something else here that I don't get?

这确实是一种主观意见。优点是构造函数可以决定返回不同的值,这使得它更加灵活。另一方面,我认为不返回值比反过来更常见。

关于函数(构造函数)返回类型中的 Javascript 奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22211583/

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