gpt4 book ai didi

javascript - "this"闭包函数内

转载 作者:行者123 更新时间:2023-11-28 11:57:28 26 4
gpt4 key购买 nike

this 在闭包内。需要注意的是,闭包不能使用 this 关键字访问外部函数的 this 变量,因为 this 变量只能由函数本身访问,而不能由内部函数访问。

例如:

var user = {
tournament:"The Masters",
data :[
{name:"T. Woods", age:37},
{name:"P. Mickelson", age:43}
],

clickHandler:function () {
// the use of this.data here is fine, because "this" refers to the user object, and data is a property on the user object.

this.data.forEach (function (person) {
// But here inside the anonymous function (that we pass to the forEach method), "this" no longer refers to the user object.
// This inner function cannot access the outer function's "this"

console.log ("What is This referring to? " + this); //[object Window]

console.log (person.name + " is playing at " + this.tournament);
// T. Woods is playing at undefined
// P. Mickelson is playing at undefined
})
}

}

user.clickHandler(); // What is This referring to? [object Window]

我的问题是:为什么下面某个函数this引用的是jquery的按钮对象而不是窗口对象。毕竟,回调函数(某些函数)仍然在另一个函数(点击)内部。

$("button").click (some function);

此外,我查看了另一个类似的问题,但我仍然不知道。 "this" keyword inside closure

最佳答案

My question is: Why is this of some function below referring to jquery's button object instead of the window Object.

因为 jQuery 通过 Function#call function 显式调用处理程序设置 this 的含义(或者可能是 Function#apply ,我必须查看 jQuery 源代码)。

这是使用call的简单示例:

function foo() {
console.log("this.answer = " + this.answer);
}

var obj = {answer: "42"};
foo.call(obj); // The first argument is used as `this` during the call

这将输出

this.answer = 42

关于javascript - "this"闭包函数内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20242351/

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