gpt4 book ai didi

javascript - 如何用 CoffeeScript 编写 $(this) ?

转载 作者:行者123 更新时间:2023-11-28 13:37:52 25 4
gpt4 key购买 nike

我的 CoffeeScript 代码:

a = (argu='.a') =>
$(argu).on 'click', () =>
$(this)

编译为 Javascript:

var a,
_this = this;

a = function(argu) {
if (argu == null) {
argu = '.a';
}
return $(argu).on('click', function() {
return $(_this);
});
};

我希望 this 是 $(argu) 或 $('.a') 而不是 _this。

如何写'this'可以引用$(argu)?

最佳答案

内在fat arrow (=>) 是您在点击处理程序中最终得到 _this 的原因。如果您使用普通箭头,您将得到您想要的:

a = (argu='.a') =>
$(argu).on 'click', -> # you can also remove the empty ()s
$(this)

编译为

var a,
_this = this;

a = function(argu) {
if (argu == null) {
argu = '.a';
}
return $(argu).on('click', function() {
return $(this);
});
};

这是因为

the fat arrow => can be used to both define a function, and to bind it to the current value of this, right on the spot.

而“瘦”箭头定义了一个函数,但没有将其绑定(bind)到特定的上下文。

<小时/>

现在,如果您确实希望回调中的 this$(argu) – 请注意,这将成为非惯用的 jQuery,因为回调中的 this 不会引用被单击的元素 - 您可以执行以下操作:

a = (argu='.a') =>
$argu = $(argu)
$argu.on 'click', (-> $(this)).bind($argu)

需要明确的是:我不建议这样做。

关于javascript - 如何用 CoffeeScript 编写 $(this) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20087027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com