谁能解释一下为什么下面的“this”指向 DOM 对象而不是 Window?
$("a").click(function() {
console.log(this);
});
这会产生:
<a id="first" href="http://jquery.com">
考虑以下应该是相同的场景:
function Foo() {
this.click = function(f) {
f();
}
}
var obj = new Foo();
obj.click(function() {
console.log(this);
});
我们在这里得到的是窗口对象(我所期望的)。
最佳答案
在 Javascript 中,OOP 与您在 Java 等语言中所习惯的不同。
基本上,更容易认为没有 OOP 而 this
只是函数的一个“隐藏参数”。
例如,当你看到
function f(x, y, z) {
console.log(this, x, y, z);
}
认为在常见的 OOP 语言(例如 Java)中会是
function f(this, x, y, z) {
console.log(this, x, y, z);
}
当你看到 var a = b.f(x, y, z);
,想var a = f(b, x, y, z)
.
当你看到 var a = f(x, y, z);
想想var a = f(undefined, x, y, z);
(在浏览器环境下,strict mode未激活时为f(window, x, y, z);
)
现在应该更容易理解为什么this
了。在您的示例中,嵌套范围中的含义不同。
关于javascript - Javascript 中 'this' 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11289668/