“var self = this”背后的理由是什么?进场? [英] What is the rationale behind the "var self = this" approach?
问题描述
可能重复:
JS:var self = this?
查看任意代码时用JavaScript编写(例如在GitHub上),许多开发人员使用 var self = this
然后使用 self
而不是 this
引用当前对象。
When looking at arbitrary code written in JavaScript (e.g. on GitHub), many developers use var self = this
and then use self
instead of this
to reference the current object.
这种方法的基本原理是什么?
What is the rationale behind this approach?
推荐答案
这个
的值是上下文的。编写 var self = this
是一种在一个上下文中保存 this
的值的方法,以便它可以用于另一个。
The value of this
is contextual. Writing var self = this
is a way to save the value of this
in one context so that it can be used in another.
示例:
function Test() {
var self = this;
console.log(this);
setTimeout(function() {
console.log(this);
console.log(self);
}, 1000);
}
打印:
Test {}
Window 11918143#comment15869603_11918143
Test {}
请注意,此
的值已更改,但我们仍然可以使用 self $ c来引用原始值$ c>。
Notice that the value of this
has changed, but we can still refer to the original value using self
.
这是有效的,因为JavaScript中的函数关闭它们的词法范围中的变量(这只是一种更为技术性的方式来说内部函数可以查看外部函数中声明的变量)。这就是为什么我们写 var self = this
;变量 self
可用于所有内部函数,即使这些函数在外部函数返回后很久才执行。
This works because functions in JavaScript "close over" the variables in their lexical scope (which is just a more technical way of saying that the inner function can see variables declared in the outer function). This is why we write var self = this
; the variable self
is available to all inner functions, even if those functions don't execute until long after the outer function has returned.
这篇关于“var self = this”背后的理由是什么?进场?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!