问题
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