fli*_*liX 5 javascript jquery this
有人可以解释一下为什么'this'在下面指向DOM对象而不是Window?
$("a").click(function() {
console.log(this);
});
Run Code Online (Sandbox Code Playgroud)
这导致:
<a id="first" href="http://jquery.com">
Run Code Online (Sandbox Code Playgroud)
考虑以下应该是相同的场景:
function Foo() {
this.click = function(f) {
f();
}
}
var obj = new Foo();
obj.click(function() {
console.log(this);
});
Run Code Online (Sandbox Code Playgroud)
我们得到的是Window Object(我所期待的).
在Javascript中,OOP与您在Java等语言中习惯使用的不同.
基本上,更容易认为没有OOP,这this
只是函数的"隐藏参数".
例如,当你看到
function f(x, y, z) {
console.log(this, x, y, z);
}
Run Code Online (Sandbox Code Playgroud)
认为在常见的OOP语言(如Java)中会有
function f(this, x, y, z) {
console.log(this, x, y, z);
}
Run Code Online (Sandbox Code Playgroud)
当你看到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);
(在浏览器环境中,当没有激活严格模式时,它是f(window, x, y, z);
)
现在应该更容易理解为什么this
在您的示例中表示嵌套作用域中的不同内容.
这取决于执行函数的上下文.jQuery显式更改了回调函数的上下文,而您的函数在全局上下文中执行该函数.
改变背景:
function Foo() {
this.click = function(f) {
f.apply(this);
}
}
Run Code Online (Sandbox Code Playgroud)
要么
function Foo() {
this.click = function(f) {
this.f = f
this.f();
}
}
Run Code Online (Sandbox Code Playgroud)
进一步阅读:
http://dailyjs.com/2012/06/18/js101-this/
http://dailyjs.com/2012/06/25/this-binding/
归档时间: |
|
查看次数: |
943 次 |
最近记录: |