我以为我终于了解了Javascript范围 [英] Just when I think I finally understand Javascript scope
问题描述
我碰到的东西可以说明我显然还没有得到它.
I run in to something that illustrates how I clearly don't get it yet.
任何人都可以解释为什么"this"的值在下面发生变化吗?
Can anyone please explain why the value of "this" changes in the following?
var MyFunc = function(){
alert(this);
var innerFunc = function(){
alert(this);
}
innerFunc();
};
new MyFunc();
推荐答案
在JavaScript中, this
表示在其上调用的上下文对象,而不是该对象的作用域它的定义(或调用范围).对于 MyFunc
,这引用了正在创建的新对象.但是对于 innerFunc
,它引用了全局对象,因为在调用 innerFunc
时未指定上下文.
In JavaScript, this
represents the context object on which the function was called, not the scope in which it was defined (or the scope in which it was called). For MyFunc
, this references the new object being created; but for innerFunc
, it references the global object, since no context is specified when innerFunc
is called.
这往往会使那些习惯于Java或类似OO语言的语言绊倒,其中 this
几乎总是引用定义了被调用方法的类的实例.请记住:JavaScript没有方法.或类.只是对象和功能.
This tends to trip up those used to Java or similar OO languages, where this
almost always references an instance of the class on which the method being called is defined. Just remember: JavaScript doesn't have methods. Or classes. Just objects and functions.
这篇关于我以为我终于了解了Javascript范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!