我刚才在写一些 CoffeeScript,遇到了一个奇怪的错误:
TypeError: Thing(param) 不是构造函数
但确实如此!当我在控制台中尝试时:
var that = new Thing(param);
that.doesSomething();
经过一番困惑,我查看了编译后的源代码,发现 coffee
将 that = new Thing param
编译为 that = new(Thing(参数));
。诡异的;我以前从没见过。所以我立即尝试:和 tada!现在我可以复制了:
var that = new(Thing(param));
that.previousLineErrorsOut();
(顺便说一下,the CoffeeScript generator on its home page 生成了 new Thing()
形式。剧情变粗了...)
我还尝试使用 native 构造函数(new Worker("somefile")
和 new(Worker("somefile"))
),它们的行为“正确” ,也就是说,这两种形式之间没有区别。
所以我完全糊涂了:new()
是什么?为什么在某些情况下会失败? 为什么 CoffeeScript 将我完美的 new
转换为 new()
?
最佳答案
new
采用表示构造函数的表达式和可选的括在括号中的参数列表。例如:
new Thing; // equivalent to next line
new Thing(); // most common form
new (function() {})(); // calls the anonymous function as a
// constructor with no arguments
new (function() {}); // equivalent to previous; if no arguments are
// specified to new, it will call with no arguments
当你这样做时:
new(Thing(param));
它试图运行使用参数 param
调用 Thing
的结果作为不带参数的构造函数。 new
后的括号使 Thing(param)
成为表示构造函数的表达式。由于 Thing
在您的情况下不返回构造函数,因此它失败了。它大致等同于:
var clazz = Thing(param);
var instance = new clazz();
我不知道为什么 CoffeeScript 会这样转换它。
关于javascript - new Thing(param) 和 new(Thing(param)) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7898820/