new Thing(param)和new(Thing(param))的区别是什么?

What's the difference between new Thing(param) and new(Thing(param))?

本文关键字:Thing new param 是什么 区别      更新时间:2023-09-26

刚才我正在写一些CoffeeScript,得到一个奇怪的错误:

TypeError: Thing(param) is not a constructor

但它是!当我在控制台中尝试时:

var that = new Thing(param);
that.doesSomething();

在有点困惑之后,我查看了编译后的源代码,发现coffeethat = new Thing param编译为that = new(Thing(param));。奇怪的;我从来没见过。所以我马上试了试:结果呢!现在我可以复制:

var that = new(Thing(param));
that.previousLineErrorsOut();
(顺便提一下,CoffeeScript生成器在其主页上生成new Thing()表单。情节越来越复杂…)

我还尝试了原生构造函数(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));

它试图运行带有参数paramThing调用的结果作为没有参数的构造函数。new后面的括号使Thing(param)成为表示构造函数的表达式。由于Thing在您的例子中没有返回构造函数,因此它失败了。大致相当于:

var clazz = Thing(param);
var instance = new clazz();

我不知道CoffeeScript为什么会这样转换

类构造函数调用

的区别
new Thing(params)

和类函数调用

Thing(params)

是,在第一种情况下,this关键字在函数体内被绑定到正在创建的对象,而在第二种情况下,它被绑定到全局对象(浏览器中的窗口)

new(Thing(params))

是一种非常奇怪的形式,在这种形式中,Thing首先像函数一样被调用,然后它的结果将作为没有参数的构造函数与new字进行比较。

你的CS把它编译成那样真是太奇怪了。

我在官方网站(http://jashkenas.github.com/coffee-script/, Try Coffeescript选项卡)上尝试了一下,它编译了

that = new Thing param

var that;
that = new Thing(param);