以下有什么区别:
new Backbone.Router.extend({initialize: function(){console.log("Created")}});
和
new (Backbone.Router.extend({initialize: function(){console.log("Created")}}));
为什么底部的输出“已创建”到控制台而顶部的没有?为什么它们如此不同?
更有趣的是:
var tmp = new Backbone.Router.extend({initialize: function(){console.log("Created")}});
new tmp();
产生错误。
然而,以下输出“已创建”。
var tmp = Backbone.Router.extend({initialize: function(){console.log("Created")}});
new tmp();
那么它们为什么不同以及如何不同?
最佳答案
我不是 backbone.js 用户,但我仍然可以回答这个问题,因为它主要与原生 javascript 有关。
第一个陈述的解释:
// All this does is to return the constructor to the variable router
var router = new Backbone.Router.extend({initialize: function(){console.log("Created")}});
// To initiatize an instance you do this. This should print "created" in the console.
var obj = new router;
在第二个语句中,您将上述两行代码合二为一。首先执行括号,即返回构造函数。然后,'new' 创建一个实例:
// This is just a short-hand way to execute both the above statements at once
var obj = new (Backbone.Router.extend({initialize: function(){console.log("Created")}}));
希望这对您有所帮助。
关于javascript - new Backbone.Router.extend ...在没有括号的情况下使用它时的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20436715/