如何在CoffeeScript fat-arrow回调中引用实际的“this”? [英] How do I refer to actual 'this' inside CoffeeScript fat-arrow callback?
问题描述
标题说的一切。当我在CoffeeScript中使用fat-arrow时,它会先调用 this
。例如:
The title says it all. When I use the fat-arrow in CoffeeScript, it stores this
first before calling the function. For example:
class myClass
constructor: ->
element = $ "#id"
element.click ->
@myMethod(@value)
return
return
myMethod: (c)->
window.console.log(c)
return
p>
would yield
var myClass;
myClass = (function() {
function myClass() {
var element;
element = $("#id");
element.click(function() {
this.myMethod(this.value);
});
return;
}
myClass.prototype.myMethod = function(c) {
window.console.log(c);
};
return myClass;
})();
现在JavaScript的第8行, this.myMethod
是错误的。在这个范围中, 指的是
元素
,而不是类 MyClass $ c $
Now on line#8 of JavaScript, this.myMethod
is wrong. In this scope, this
refers to element
instead of the class MyClass
.
然而,如果在CoffeeScript的第4行,我将 element.click - >
替换为 element.click =>
JavaScript中的第8行将变为 _this.myMethod(_this.val)
code> this 引用myClass在调用函数之前存储在 _this
中。但是 _this.value
是未定义的,即使它被定义,我试图访问的对象是 element
(这是由该函数范围内的实际 this
关键字引用的)。
However, if on line#4 of CoffeeScript, I replace element.click ->
by element.click =>
the line#8 in JavaScript will become _this.myMethod(_this.val)
where this
referring to myClass is stored in _this
before calling the function. But _this.value
is undefined and even if it were defined, the object I'm trying to access here is element
(which is referred to by the actual this
keyword in scope of this function).
如何访问实际现在
How would access the actual this
now?
推荐答案
方法。第一个是:
class myClass
constructor: ->
element = $ "#id"
element.click =>
@myMethod(element.value)
return
return
myMethod: (c) ->
window.console.log(c)
return
class myClass
constructor: ->
element = $ "#id"
myMethodCallback = (c) => @myMethod(c)
element.click ->
myMethodCallback(@value)
return
return
myMethod: (c) ->
window.console.log(c)
return
如下所示。我不确定jQuery API的用法,所以更好地检查适当的文档页< a>。
The 3rd one is as showed below. I'm not sure about jQuery API usage though, so better check on appropriate docs page.
class myClass
constructor: ->
element = $ "#id"
element.click (event) =>
@myMethod(event.target.value)
return
return
myMethod: (c) ->
window.console.log(c)
return
第一种方式,因为它似乎更直接。
这个或者其他的,但你需要决定'这个'你想在element.click回调的作用域。不可能同时访问两个thises。
I would prefer the 1st way as it seems to be more straightforward. This or the other but you need to decide 'which this' you would like to have in scope of the element.click callback. It's not possible to access two 'thises' at the same time.
顺便说一句。所有这些返回语句似乎不必要。最短的工作解决方案如下:
By the way. All those return statements seems unnecessary. The shortest working solution would look like:
class myClass
constructor: ->
element = $ "#id"
element.click => @myMethod(element.value)
myMethod: (c) -> window.console.log(c)
这篇关于如何在CoffeeScript fat-arrow回调中引用实际的“this”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!