在嵌套函数中引用类对象时出现问题

Trouble referencing class object inside a nested function

本文关键字:问题 对象 嵌套 函数 引用      更新时间:2023-09-26

我正在尝试用coffeescript创建一个类,我几乎做到了。我的问题是,我想为类的整个范围创建几个变量,但我不知道如何在嵌套函数中使用它们。@相当于"this。",但是我希望能够从类内的任何位置获取这些构造函数属性。

示例:

class CoffeeScriptClass
  constructor: (@foo) ->
  _sampleFunction: ->
    $.each BigArray, (index, NestedArray) ->
      $.each NestedArray, (index, widget) ->
        ## I'd like @foo to reference the constructor value
        widget = @foo 
        return
      return  
    return

这有道理吗?我确实在努力保持OO Javascript的整洁和有序,但我在coffescript的范围界定部分遇到了困难。我很乐意为班上其他同学提供任何重构/建议。谢谢大家。

您需要确定内部函数的范围:

class CoffeeScriptClass
  constructor: (@foo) ->
  _sampleFunction: ->
    $.each BigArray, (index, NestedArray) => // keep parent scope
      $.each NestedArray, (index, widget) => // keep parent scope
        ## I'd like @foo to reference the constructor value
        widget = @foo 
        return
      return  
    return

以下是编译后的JS,显示了为什么这样做:

var CoffeeScriptClass;
CoffeeScriptClass = (function() {
  function CoffeeScriptClass(foo) {
    this.foo = foo;
  }
  CoffeeScriptClass.prototype._sampleFunction = function() {
    var _this = this; // reference to the class is maintained
    $.each(BigArray, function(index, NestedArray) {
      $.each(NestedArray, function(index, widget) {
        widget = _this.foo;
      });
    });
  };
  return CoffeeScriptClass;
})();