如何从闭包内部调用实例方法? [英] How to call an instance method from inside a closure?

查看:14
本文介绍了如何从闭包内部调用实例方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问 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'

这是上述代码的功能链接

推荐答案

有多种方法可以解决这个问题.

There are various ways to deal with this.

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):

  1. 保存对 @ 的引用,这样您就不必关心回调函数内部的 this 是什么:

  1. Save a reference to @ so that you don't have to care what this is inside the callback function:

_this = @
@an_array.map (value) -> _this.a(value)

演示:http://jsfiddle.net/ambiguous/XhP4z/

由于 window.self 以及如果您忘记 JavaScript 中的 var.

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:

  1. 如果您尝试绑定来自其他地方的函数,则不能使用 =>,因此您需要使用 (2)(3) (或可能 Function.callFunction.apply).
  2. 如果您同时需要内部和外部 this,那么您会选择 (1).
  3. 如果您需要手动绑定一个函数,但不确定是否存在原生 bind,那么您可能最终会得到 (3) 以及哪个分支(3) 可能取决于您已经拥有的库.
  4. ...
  5. 利润.
  1. 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 possibly Function.call or Function.apply).
  2. If you need both the inner and outer this at the same time then you'd go with (1).
  3. 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.
  4. ...
  5. Profit.

这篇关于如何从闭包内部调用实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆