新东西(param)和新东西(东西(param))有什么区别?

时间:2011-10-26 04:48:33

标签: javascript constructor new-operator coffeescript

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

TypeError: Thing(param) is not a constructor

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

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

经过一些混乱后,我查看了已编译的源代码,发现coffeethat = new Thing param编译为that = new(Thing(param));。奇怪的;我以前从未见过这个。所以我及时尝试一下:tada!现在我可以复制:

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

(顺便提一下,the CoffeeScript generator on its home page会生成new Thing()表格。情节变浓......)

我也尝试使用本机构造函数(new Worker("somefile")new(Worker("somefile"))),它们的行为“正确”,即两种形式之间没有区别。

所以我很困惑:什么是new()?为什么在某些情况下会失败? 为什么CoffeeScript会将我完全正常的new转换为new()

2 个答案:

答案 0 :(得分:1)

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));

尝试使用参数Thing作为没有参数的构造函数运行调用param的结果。 new后的括号使Thing(param)表达构造函数的表达式。由于Thing在您的情况下不返回构造函数,因此失败。它大致相当于:

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

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

答案 1 :(得分:1)

类似构造函数的调用之间的区别

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);
相关问题