Trouble referencing class object inside a nested f

2019-08-12 16:23发布

I'm trying to create a class in coffeescript and I'm almost there. My problem is, I'd like to create a couple of variables for the entire scope of the class, however I don't know how to get to them inside nested functions. @ is equivalent to "this.", however I'd like to be able to get to those constructor properties from anywhere inside the class.

Example:

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

Does this make sense? I'm really trying to keep my OO Javascript tidy and organized, but I'm having a difficult time with the scoping part of coffeescript. I'll happily welcome any refactoring/advice on the rest of my class. Thanks all.

1条回答
Evening l夕情丶
2楼-- · 2019-08-12 16:52

You need to scope the inner functions:

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

Here is the compiled JS showing why this works:

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;

})();
查看更多
登录 后发表回答