这两种实现之间有什么区别
What's the different between these two implementations
片段 A:
DemoFilter =
onConfirmed: (cb) ->
cb()
a =
onConfirmed: (callback) ->
this.callback = callback
confirm: ->
this.callback()
b =
init: ->
a.onConfirmed =>
DemoFilter.onConfirmed @mycallback
mycallback: =>
console.log this # output: {} or Object window on browser
b.init()
a.confirm()
片段 B:
DemoFilter =
onConfirmed: (cb) ->
cb()
a =
onConfirmed: (callback) ->
this.callback = callback
confirm: ->
this.callback()
b =
init: ->
a.onConfirmed =>
DemoFilter.onConfirmed =>
console.log this # output: Object b
# mycallback: =>
# console.log this
b.init()
a.confirm()
为什么这些console.log
输出不一样?
在节点环境中:
A:输出{}
B:输出Object b
发现编译的结果完全一样,我无法弄清楚为什么结果不同。
您在这里的问题是您使用的是简单对象而不是类,因此=>
行为不符合您的预期。当你这样说时:
o =
m: =>
这完全等同于说:
f = =>
o =
m: f
这意味着m
内部的@
(AKA this
)是全局对象(window
浏览器中或 AFAIK,node.js 中的空对象),而不是您期望的o
。
当你说:
class C
m: =>
当您说o = new C
时,CoffeeScript 会将m
绑定到C
实例。如果使用纯对象文本而不是类,则没有特殊的构造阶段来设置绑定,也没有=>
将函数绑定到的类实例。
如果我们回到你的第一个案例:
b =
init: ->
a.onConfirmed =>
DemoFilter.onConfirmed @mycallback
mycallback: =>
console.log this
mycallback
将绑定到全局对象的任何内容。此外,@
的值(AKA this
)取决于函数的调用方式,而不是定义函数的位置(当然是绑定函数),所以如果你说:
b.init()
那么@
里面init
就会b
.然后你交给a.onConfirmed
的匿名函数:
a.onConfirmed =>
DemoFilter.onConfirmed @mycallback
将绑定到 b
,因为定义该函数时@
b
。但是mycallback
不会关心,因为它已经绑定到全局对象。
在第二种情况下:
b =
init: ->
a.onConfirmed =>
DemoFilter.onConfirmed =>
console.log this
当调用init
时,我们再次@
b
,传递给a.onConfirmed
的匿名函数将再次绑定到b
。这意味着当:
DemoFilter.onConfirmed => ...
被称为,@
将再次b
.这里我们还有另一个匿名绑定函数,由于@
在此级别b
,因此在调用console.log this
时b
this
(AKA @
如果您使用类而不仅仅是对象:
class A
onConfirmed: (@callback) ->
confirm: ->
@callback()
class B
constructor: (a) ->
a.onConfirmed =>
DemoFilter.onConfirmed @mycallback
mycallback: =>
console.log @
a = new A
b = new B(a)
a.confirm()
然后,您应该会看到您期望的行为。
相关文章:
- 全局变量和全局对象的属性之间有什么区别吗
- 在ember/handlers中使用value和valueBinding有什么区别
- 这两个关于 JavaScript 作用域链的例子有什么区别?
- Math.min()和Math.max()之间有什么区别?在Javascript中
- angularjs中的ng网格和ui网格有什么区别
- webpack开发模式和生产构建模式之间有什么区别
- 缓存!saveLocations()和addLocation()函数有什么区别
- 关于承诺/A+规范,术语“当时可”和“承诺”之间有什么区别
- 以下两者在javascript中有什么区别
- jquery.js和jquery.lite.js有什么区别
- 通过Nuget安装Angular JS和Angular JS核心有什么区别
- XMLHttpRequest对象的open()和send()方法之间有什么区别
- 这两种不同的创建对象文字的方法有什么区别
- jQuery中这两个词有什么区别
- 在Javascript语法中:和::和:::有什么区别
- getElementById 和 getElementsByClassName 有什么区别?
- (typeof variable === “function”) 和 jQuery.isFunction() 有什么区别
- 在使用JS的Ajax调用中,ajaxComplete和beforesend之间有什么区别
- $(e.target).find和template.find('input').value之间有什么区别
- 在javascript中,在变量名之前使用var有什么区别/优势吗