CoffeeScript 中的类指针?
试图弄清楚如何在 CoffeeScript 中编写以下内容:
var foo = new function()
{
var $this = this;
$("#foo").click( this.clicked );
this.clicked = function()
{
$this.alert( $(this).text() );
};
this.alert = function(message)
{
alert(message);
};
};
不幸的是,我一生都无法弄清楚如何在 CoffeeScript 中访问类指针,“this”显然不是上下文感知的,并且通常只会指向传递的变量由被叫方。所以我没有办法用 CoffeeScript 编写上面的脚本。
有什么建议吗?我在文档中找不到任何有用的东西,你有 @ 指针,但它们也只是使用当前上下文中的“this”指针,使其毫无用处。
trying to figure out how to write the following in CoffeeScript:
var foo = new function()
{
var $this = this;
$("#foo").click( this.clicked );
this.clicked = function()
{
$this.alert( $(this).text() );
};
this.alert = function(message)
{
alert(message);
};
};
Unfortunately I can't figure out for the life of me how in CoffeeScript I access the class pointer, "this" is obviously not context aware and will often just point to the variable passed by the callee. So there's no way for me to write the above script in CoffeeScript.
Any advice? I can't find anything useful in the documentation, you have the @ pointers but they also just use the "this" pointer from the current context, making it useless..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在构造函数中直接向
@
添加方法来达到相同的效果:Demo: http ://jsfiddle.net/ambigously/Y8ZBe/
你通常可以使用绑定方法和一个不过,在这样的情况下,“事件”参数:
这种事情通常出现在 jQuery(或类似)回调中,并且它们通常有一个事件参数,它显式标识目标“
this
”,以便您可以使用绑定函数。演示:http://jsfiddle.net/ambigously/LafV2/
You can add methods directly to
@
in the constructor to achieve the same effect:Demo: http://jsfiddle.net/ambiguous/Y8ZBe/
You'd usually be able to use a bound method and an "event" argument in situations like this though:
This sort of thing usually turns up in jQuery (or similar) callbacks and they usually have an event argument which explicitly identifies the target "
this
" so that you can use bound functions.Demo: http://jsfiddle.net/ambiguous/LafV2/
CoffeeScript 仍然是 javascript。
this
的限制仍然适用。显然你可以直接写一个翻译:然而你应该使用原型(即使是在 javascript 中)。使用粗箭头
=>
您可以将函数绑定到它的当前上下文(但随后您会丢失元素引用):或者使用
class
抽象(只不过是原型用法包含在一个更漂亮的包中)和jQuery.proxy
:$.proxy @clicked,在现代浏览器/引擎上,此
可以替换为@clicked.bind @
(请参阅Function.prototype.bind
)。CoffeeScript is still javascript. The limitations of
this
still apply. You can obviously write a straight translation:Yet you should be using prototypes (even in javascript). With the fat arrow
=>
you can bind the function to it's current context (but then you lose the element reference):Or using the
class
abstraction (nothing more than prototype usage wrapped up in a prettier package) andjQuery.proxy
:$.proxy @clicked, this
could be replaced with@clicked.bind @
on modern browsers/engines (seeFunction.prototype.bind
).