以下之间的区别是什么:
new Backbone.Router.extend({initialize: function(){console.log("Created")}});
和
new (Backbone.Router.extend({initialize: function(){console.log("Created")}}));
为什么底部的一个输出"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")}}));
希望这能有所帮助。