JavaScript和'this'在立即执行的函数内部
JavaScript and 'this' inside immediately executed functions
我一直在阅读JavaScript中"this"的复杂性。给定以下代码:
$(document).ready(function() {
console.dir(this);
(function foo() {
console.dir(this);
})();
});
在Chrome中,控制台显示第一个'this'作为'HTMLDocument'(如我所料),但第二个'this'是'undefined'。有人能给我一个好的解释吗?
调用javascript函数的方式改变了其中this
的含义。在这里,您调用了一个没有与任何对象关联的方法,因此它没有要绑定的this
值。
在第一种情况下,回调是通过JQuery调用,他们正在操纵回调,使this
指向document
DOM元素。很容易将其可视化为使用apply
yourCallback.apply(document, null);
你可以像这样修复第二个版本
$(document).ready(function() {
console.dir(this);
var that = this;
(function foo() {
console.dir(that);
})();
});
或者用apply
$(document).ready(function() {
console.dir(this);
(function foo() {
console.dir(this);
}).apply(this, null);
});
this
是当前函数被调用的上下文。
- 当使用object.method()语法调用函数时,
object
成为上下文。 - 使用function()语法调用函数时,没有上下文:它是空的。
document
作为上下文调用ready函数。你调用你的立即执行的函数没有上下文,这就是为什么它是空的。
你可以这样做:
// assign `this` to that so you can access `this` through `that`
var that = this;
(function foo() {
console.log(that);
}());
或:
// bind the function to `this` and then call it
$.proxy(function() {
console.log(this);
}, this)();
参见jQuery.proxy
或者
// call the function with `this` as context
(function() {
console.log(this);
}).call(this);
参见Function.call
如果将该代码放入加载了jQuery的页面控制台,则第二个"this"是DOMWindow,它是全局的"this"。不是 undefined
你的页面上一定有别的东西
第二个this
在一个没有上下文的匿名函数中。this
始终是函数级别的隐式变量,因此您的内部函数this
遮蔽了外部this
相关文章:
- 如何做到这一点,使代码在不传递条件后执行函数
- javascript自执行函数-不同的语法
- JavaScript:只有当数组中的所有项都为true时才执行函数
- iFrame url更改时执行函数
- 为什么AngularJS在每个摘要循环上都执行函数
- 如何使用setInterval执行函数
- 当*ngFor以角度2结束时执行函数
- Ajax调用完成后如何执行函数
- 在显示引导弹出窗口之前执行函数
- 从自执行函数返回函数的Javascript性能命中率
- 在操作完成时执行函数
- jquery/js中的自执行函数
- 如何仅在完成对gap.client.youtube的请求.execute后执行函数
- 构造函数函数中的自执行函数的OO上下文/范围
- Javascript未使用=运算符执行函数
- AngularJS:如何按照预定义的顺序执行函数
- 在不使用隔离作用域的情况下执行函数的角度指令
- 如何在页面加载后执行函数是在 AngularJS 中完成的
- 完成页面加载后执行函数
- 如何在完成完全执行函数后触发循环