如何从闭包中调用实例方法? [英] How to call an instance method from inside a closure?
问题描述
我试图访问一个实例方法在 map
调用,不幸的是我的实例对象的引用被重新定义为Window。我不知道如何获取我的实例方法:
I'm trying to access an instance method inside of a map
call, unfortunately my reference to the instance object is being redefined to Window. I'm not sure how to get a hold of my instance method:
class Test
constructor: (@an_array) ->
f: () ->
@an_array.map (value) ->
@a(value)
a: (value) ->
alert value
t = new Test [1, 2, 3]
t.f() // TypeError: Object [object Window] has no method 'a'
推荐答案
有多种方法来处理。
CoffeeScript中最常见的是使用胖箭头 =>
)以产生绑定函数:
The most common in CoffeeScript would be to use a fat arrow (=>
) to produce a bound function:
@an_array.map (value) => @a(value)
演示: http://jsfiddle.net/ambiguous/6BW8q/
标准的JavaScript方法也可以工作有时是必要的或更合适的):
The standard JavaScript approaches will also work (and sometimes would be necessary or more appropriate):
-
保存对
@
这样你不必关心这个
是否在回调函数中:
Save a reference to
@
so that you don't have to care whatthis
is inside the callback function:
_this = @
@an_array.map (value) -> _this.a(value)
演示: http://jsfiddle.net/ambiguous/XhP4z/
我倾向于使用<$ c $由于存在 _this 而不是 self
org / en-US / docs / Web / API / Window / selfrel =nofollow> window.self
和
I tend to use _this
instead of self
as the name for this thing due to the existence of window.self
and the interesting bugs that causes if you forget the var
in JavaScript.
手动创建绑定函数使用 Function.bind
,但这并不是普遍支持的:
Manually create a bound function using Function.bind
, this isn't quite universally supported though:
@an_array.map ((value) -> @a(value)).bind(@)
演示: http://jsfiddle.net/ambiguous/n2XnC/
使用jQuery的 $。proxy
,Underscore的 _。bind
或其他非本地绑定函数实现:
Use jQuery's $.proxy
, Underscore's _.bind
, or some other non-native bound function implementation:
@an_array.map _((value) -> @a(value)).bind(@)
演示: http://jsfiddle.net/ambiguous/LAy9L/
您选择哪一个取决于您的环境和特定需求:
Which one you choose depends on your environment and specific needs:
- 如果您要绑定一个来自其他地方的函数,则不能使用
=>
,因此您需要使用(2) (3)(或可能Function.call
或Function.apply
)。 - 内部和外部
- 如果你需要手动绑定一个函数,但你不确定一个本地
bind
是否存在,那么你可能会遇到(3) 。
- If you're trying to bind a function that comes from elsewhere, then you can't use
=>
so you'll need to use some variant of (2) or (3) above (or possiblyFunction.call
orFunction.apply
). - If you need both the inner and outer
this
at the same time then you'd go with (1). - If you need to manually bind a function but you aren't sure that a native
bind
exists then you' probably end up with (3) and which branch of (3) would probably depend on which library you already have available. - ...
- Profit.
这篇关于如何从闭包中调用实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!