【发布时间】:2013-11-27 12:20:02
【问题描述】:
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]
我的问题是:为什么下面some function的this指的是jquery的按钮对象而不是窗口对象。毕竟回调函数(某个函数)还在另一个函数中(点击)。
$("button").click (一些函数);
另外,我查看了关于 SO 的另一个类似问题,但我仍然不明智。 "this" keyword inside closure
【问题讨论】:
标签: javascript