有以下代码:
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'。我该如何解决?谢谢!
答案 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