cuốn sách gpt4 ai đã làm

javascript - 在通过 bind() 绑定(bind)的函数中使用绑定(bind) this 和函数作用域的 this

In lại Tác giả: Walker 123 更新时间:2023-11-28 19:02:29 28 4
mua khóa gpt4 Nike

我有以下函数调用:

$(".selector").on("click", callback.bind(this, param1, param2));

在我的回调函数中,我想使用绑定(bind)的 this 以及函数作用域中的 this 。

这可以以某种方式完成吗?

câu trả lời hay nhất

Inside my callback function I would like to use the bound this as well as the this from the function scope.

在该特定示例中,您可以使用事件的currentTarget属性:

function callback(p1, p2, e) {
// Use e.currentTarget
}

请注意,我们有 p1p2,它们是绑定(bind)到回调的参数,后跟 e 这是事件单击发生时传递的参数。

但是,在一般情况下,您不需要Function#bind,因为它会阻止您访问该函数的cái này被调用。

您可以为自己提供一个 Function#curry (请参阅下文了解该名称的原因),让 cái này 单独存在,然后对当前函数进行柯里化(Currying)这个,例如:

$(".selector").on("click", callback.curry(this, param1, param2));

未优化版本的curry如下所示:

Function.prototype.curry = function() {
var f = this;
var boundArgs = Array.prototype.slice.call(arguments);
return function() {
return f.apply(this, boundArgs.concat(Array.prototype.slice.call(arguments)));
};
};

实例:

Function.prototype.curry = function() {
var f = this;
var boundArgs = Array.prototype.slice.call(arguments);
return function() {
return f.apply(this, boundArgs.concat(Array.prototype.slice.call(arguments)));
};
};

var obj = {
foo: 42,
method: function() {
$(".selector").on("click", callback.curry(this, "param1", "param2"));
}
};
obj.method();

function callback(t, p1, p2, e) {
snippet.log("t.foo = " + t.foo);
snippet.log("this.tagName = " + this.tagName);
snippet.log("e.currentTarget.tagName = " + e.currentTarget.tagName);
snippet.log("p1 = " + p1);
snippet.log("p2 = " + p2);
}
Click me



为什么 curry ?

从另一个函数创建一个函数,并预先提供该函数的(部分)参数,这通常被称为“柯里化(Currying)”,以数学家 Haskell Curry 的名字命名。它也被称为“部分应用程序”,尽管我认为(这不是我的专业领域)该术语具有稍微更具体的含义,至少在函数式编程中(例如您在 Haskell 语言中所做的那种 - 也以 Haskell Curry 命名) )。

关于javascript - 在通过 bind() 绑定(bind)的函数中使用绑定(bind) this 和函数作用域的 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32266774/

28 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress