Javascript 新主干网。路由器。扩展。。。不使用括号时的区别

Javascript 新主干网。路由器。扩展。。。不使用括号时的区别,javascript,backbone.js,constructor,underscore.js,instance,Javascript,Backbone.js,Constructor,Underscore.js,Instance,以下各项之间的区别是什么: new Backbone.Router.extend({initialize: function(){console.log("Created")}}); 及 为什么底部的一个输出“创建”到控制台,而顶部的一个没有?为什么它们如此不同? 更有趣的是: var tmp = new Backbone.Router.extend({initialize: function(){console.log("Created")}}); new tmp(); 产生一个错误 然而

以下各项之间的区别是什么:

new Backbone.Router.extend({initialize: function(){console.log("Created")}});

为什么底部的一个输出“创建”到控制台,而顶部的一个没有?为什么它们如此不同?

更有趣的是:

var tmp = new 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;
在第二条语句中,您将上述代码的两行合并为一行。首先执行括号,即返回构造函数。然后,“新建”创建一个实例:

// 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")}}));

希望这能有所帮助。

这两种说法实际上并不相同。初始化路由器实例实际上会导致JS错误。TypeError:Object[Object Object]没有方法'apply'@SimonC在问题的后半部分,请尝试将“new tmp()”更改为“new tmp”。你能告诉我你是否还有错误吗?@SimonC现在有点奇怪了。我不知道主干网的内部结构,但纯粹是从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;
// 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")}}));