问题描述
我有一个关于如何在嵌套函数场景中处理this"指针的问题.
I have a question concerning how the "this" pointer is treated in a nested function scenario.
假设我将以下示例代码插入到网页中.调用嵌套函数doSomeEffects()"时出现错误.我检查了 Firebug,它表明当我在那个嵌套函数中时,this"指针实际上指向全局window"对象——这是我没想到的.我一定没有正确理解某些东西,因为我认为既然我在对象的函数中声明了嵌套函数,它应该具有与函数相关的本地"范围(即this"指针将指代对象本身,例如在我的第一个if"语句中是怎样的).
Say I insert this following sample code into a web page. I get an error when I call the nested function "doSomeEffects()". I checked in Firebug and it indicates that when I am in that nested function, the "this" pointer is actually pointing to the global "window" object - which I did not expect. I must not be understanding something correctly because I thought since I declared the nested function within a function of the object, it should have "local" scope in relation to the function (i.e. the "this" pointer would be referring to the object itself like how it is in my first "if" statement).
任何指针(无双关语)将不胜感激.
Any pointers (no pun intended) would be appreciated.
var std_obj = {
options : { rows: 0, cols: 0 },
activeEffect : "none",
displayMe : function() {
// the 'this' pointer is referring to the std_obj
if (this.activeEffect=="fade") { }
var doSomeEffects = function() {
// the 'this' pointer is referring to the window obj, why?
if (this.activeEffect=="fade") { }
}
doSomeEffects();
}
};
std_obj.displayMe();
推荐答案
在 JavaScript 中,this
对象实际上基于您如何进行函数调用.
In JavaScript the this
object is really based on how you make your function calls.
通常有三种方法可以设置this
对象:
In general there are three ways to setup the this
object:
someThing.someFunction(arg1, arg2, argN)
someFunction.call(someThing, arg1, arg2, argN)
someFunction.apply(someThing, [arg1, arg2, argN])
在上述所有示例中,this
对象将是 someThing
.调用没有前导父对象的函数通常会得到全局对象,这在大多数浏览器中意味着 window
对象.
In all of the above examples the this
object will be someThing
.Calling a function without a leading parent object will generally get you the global object which in most browsers means the window
object.
这篇关于Javascript“这个"嵌套函数内的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!