Javascript 对象链接查询
我花了一些时间在我认为是一个错误的东西上,直到我找到了一个解决办法 我仍然不明白为什么前面的代码失败了 有什么见解吗 失败代码:Javascript 对象链接查询,javascript,coffeescript,Javascript,Coffeescript,我花了一些时间在我认为是一个错误的东西上,直到我找到了一个解决办法 我仍然不明白为什么前面的代码失败了 有什么见解吗 失败代码: getModule: -> Gmaps4Rails.Google createMap : -> new @getModule().Map() 工作代码: constructor: @module = @getModule() getModule: -> Gmaps4Rails.Google createMap : ->
getModule: ->
Gmaps4Rails.Google
createMap : ->
new @getModule().Map()
工作代码:
constructor:
@module = @getModule()
getModule: ->
Gmaps4Rails.Google
createMap : ->
new @module.Map()
原因是
新的匿名函数
与JavaScript中的新的Gmaps4Rails.Google()
不同
// Translated JavaScript code (simplified):
var your_module = {
getModule: function() {
return Gmaps4Rails.Google;
},
createMap: function() {
// This is where things go wrong
return new this.getModule().Map();
}
};
问题是返回新的this.getModule().Map()
转换为return new function(){return Gmaps4Rails.Google;}
——它忽略返回值并使用this
(这是从匿名函数继承的新对象)。因此,该行本质上转换为return{}.Map()代码>由于对象没有映射
方法,因此会出现错误
当您将@module
设置为对Gmaps4Rails.Google
的引用时,当您调用new@module.Map()时
您实际上正在调用新的Gmaps4Rails.Google
,它返回一个对象,该对象具有映射
方法,因此一切正常。如果我写了:新建this.getModule.Map()
,我会理解,但事实并非如此。这转换为:returnnewfunction(){returngmaps4rails.Google;}()
Iguess@apneadiving-本质上-将其翻译为var\u temp=function(){return Gmaps4Rails.Google;};返回新的_temp()
Sothis
继承自Gmaps4Rails.Google
然后触发this.Map()
?听起来很疯狂:)(+1同时)@apreading-不,一点也不-在损坏的版本中,匿名函数(this
)返回的值是从匿名函数继承的对象。在工作版本中,@module
是对(Gmaps4Rails.Google
)上要调用的实际函数的引用,而不是一个完全不同的(匿名)函数。这有意义吗?我想这是我能得到的最好的答案,所以我接受了,但是你知道我在哪里可以找到关于这个的理论吗?