Foreach循环链接到'this'CoffeeScript
foreach loop with link to 'this' in 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。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
相关文章:
- $(this).prop('property') vs. this.property
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 在另一个函数中使用变量this
- this.router在AngularJS 2中未定义
- reactjs this.refs vs document.getElementById
- JavaScript 中的嵌套函数和 “this” 关键字
- React+Meteor:this.ops返回未定义
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- jQuery(this).Pparent().Pparente().Prent().find()在iPad上不起作用
- Understanding Javascript scope with "var that = this&qu
- 在方法中的函数中引用 CoffeeScript 类中的“this”的最佳方式是什么?
- d3.js/CoffeeScript:访问mouseover中类和路径的执行上下文(this)
- 未捕获类型错误:this.source不是函数coffeescript错误
- 如何在CoffeeScript或JavaScript中从基类(this. constructor .name)中引用扩展
- Coffeescript - 'this'总是被'_this'在胖箭头回调
- Foreach循环链接到'this'CoffeeScript
- Coffeescript 'this' inside jQuery .each()
- jQuery / Coffeescript隐藏除$(this)之外的相关名称,不允许我勾选选择框
- 在coffeescript中使用$(this)