javascript - 使用 new 运算符返回 javascript 函数会返回奇数范围

标签 javascript new-operator

我试图理解为什么 new 针对函数运行,而不是示例中函数的返回 y =:

function returnFunction(){ return function blah(str){ this.x = str; return this;}}

y = new returnFunction()("blah")
// output: Window {x: "blah"; top: Window, window: Window, location: Location, ....}
x = new (returnFunction())("blah")
// output: blah {x: "blah"}

z = new function blah(){return this;}()
// output: blah {}

zz = new function(){return this;}() //note the missing function name
// output: Object {}

b = new function blib(str){this.x = str; return this}
// blib {x: undefined}
bb = new function blib(str){this.x = str; return this}("blah")
// blib {x: "blah"}
c = new function blib(){this.x = "blah"; return this}
// blib {x: "blah"}

因此,在 y 的情况下,new 创建 returnFunction 的副本,然后调用它

y = (new returnFunction())()

通过调用匿名函数,我们没有 this,因此它默认为 Window

对于x,通过将其包装在括号中(调用returnFunction返回blah函数),然后通过new运算符将this设置为新对象来调用blah

这似乎很奇怪,我必须包装 new (returnFunction()) 才能使其以正确的顺序执行。

有人可以向我解释一下底层的执行吗?

最佳答案

关于javascript - 使用 new 运算符返回 javascript 函数会返回奇数范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263368/

相关文章:

javascript - 跳过 json 对象(PHP session )

javascript - 如何在 2 个 <div> 之间使用 html Canvas

javascript - Node.js单线程与并发

javascript - 在javascript中更新多个元素的更有效方法?

c++ - 如何使用 new 过度分配内存以在结构中分配变量?

c++ - C++对动态创建的类成员的功能的 undefined reference

javascript - DropDown 未填充到 KENDO Grid 中

c++ - 什么编译机制会转换 new 运算符的结果?

c++ - "new"没有在类中调用指定的构造函数?

c++ - 在 C++ 中监视内存分配