gpt4 book ai didi

JavaScript:为什么我的 `new` 需要括号?

转载 作者:行者123 更新时间:2023-11-28 13:34:40 25 4
gpt4 key购买 nike

我想实例化一个由函数返回的构造函数,但注意到 new 有点奇怪:

  // This function returns a constructor function
function getConstructor(){ return function X(){this.x=true} }

getConstructor(); //=> function X(){this.x=true}
new getConstructor(); //=> function X(){this.x=true}

new (getConstructor()); //=> X {x: true}

为什么需要括号?

最佳答案

在第一种情况下,new 调用 getConstructor 函数作为对象的“构造函数”。该函数返回另一个函数(您已明确设置它) - 这就是为什么 function X(){this.x=true} 是输出。

在第二种情况下,括号使 new 关键字调用该函数,该函数是从 getConstructor 执行中返回的。

为了更好地理解:

function getConstructor(){ return function X(){this.x=true} }

var func = getConstructor(); //=> function X(){this.x=true}
var instance = new func(); //=> X {x: true}

关于JavaScript:为什么我的 `new` 需要括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22344527/

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