foreach循环,在CoffeeScript中链接到'this'

时间:2015-08-19 12:33:39

标签: javascript coffeescript

有以下代码:

  User.prototype.convertFromPermissionsToScopes = ->
    this.scopes = {}
    scopesNames = ['create', 'delete', 'update', 'show']
    for groupName of this.permissions
      this.scopes[groupName] = {}
      scopesNames.forEach (scopeName) ->
        this.scopes[groupName][scopeName] = this.permissions[groupName].indexOf(scopeName) isnt -1

我在最后一行收到错误'this.scopes is undefined'。我该如何解决?谢谢!

1 个答案:

答案 0 :(得分:1)

使用fat arrow将外部this传递到forEach的上下文:

scopesNames.forEach (scopeName) =>

这将确保将外部范围传递给方法的上下文。

您可以使用:: prototype@ this旁边的旁注:

User::convertFromPermissionsToScopes = ->
  @scopes = {}
  scopesNames = ['create', 'delete', 'update', 'show']
  for groupName of @permissions
    @scopes[groupName] = {}
    scopesNames.forEach (scopeName) =>
      @scopes[groupName][scopeName] = @permissions[groupName].indexOf(scopeName) isnt -1