Trouble referencing class object inside a nested function

[亡魂溺海] 提交于 2020-01-05 05:49:29

问题


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:


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;

})();


来源:https://stackoverflow.com/questions/18281886/trouble-referencing-class-object-inside-a-nested-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!