Foreach循环链接到'this'CoffeeScript

foreach loop with link to 'this' in CoffeeScript

本文关键字:this CoffeeScript 循环 链接 Foreach      更新时间:2023-09-26

代码如下:

  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。scope is undefined'在最后一行。我该怎么修理它?谢谢!

使用fat箭头将外部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