new Thing(param)和new(Thing(param))的区别是什么?
What's the difference between new Thing(param) and new(Thing(param))?
刚才我正在写一些CoffeeScript,得到一个奇怪的错误:
TypeError: Thing(param) is not a constructor
但它是!当我在控制台中尝试时:
var that = new Thing(param);
that.doesSomething();
在有点困惑之后,我查看了编译后的源代码,发现coffee
将that = 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));
它试图运行带有参数param
的Thing
调用的结果作为没有参数的构造函数。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);
- 使用:new Image()控制加载html.src=html_URL
- 如何在不使用 new 关键字的情况下从函数创建对象
- 为什么要做新的.Date()与new相差1小时.日期().到ISOString()
- “createImageData()”和“new ImageData(()”有何不同
- 返回值+new Date()与Date.now()是否不同
- new SharedWorker(“whatever.js”)返回一个错误
- new Datamap() 在调用之间保持内存的共享状态
- new XMLHttpRequest().responseType empty
- a=1和a=new Number()之间的差异
- JavaScript“new Date()”使用哪个时区
- JS new.target vs. instanceof
- 为什么(new RegExp(“w”)==/w/)在JS中为false
- JavaScript-使用B.prototype=new A()继承数组
- 为什么使用“new”创建一个Javascript数组被认为是不好的
- “new”关键字是在构造对象时自动设置“constructor”属性的唯一方法吗
- typeof new Function()总是“;函数”;
- new Date('2011-12-15 00:00:00') is showing up as NaN
- infobox.prototype=new google.maps.overlayview()错误,未定义google
- 为什么new Date()会删除一天?-Javascript
- new Thing(param)和new(Thing(param))的区别是什么?