Javascript“this”嵌套函数内的指针 [英] Javascript "this" pointer within nested function

查看:137
本文介绍了Javascript“this”嵌套函数内的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于如何在嵌套函数场景中处理this指针的问题。



假设我将下面的示例代码插入到网页中。当我调用嵌套函数doSomeEffects()时出现错误。我检查了Firebug,它表明当我在嵌套函数中时,this指针实际上指向全局窗口对象 - 这是我没有想到的。我不能正确地理解某些东西,因为我认为自从我在对象的函数中声明了嵌套函数以来,它应该具有与该函数相关的本地范围(即,this指针将指向对象本身它是如何在我的第一个if声明)。

任何指针(没有双关意图),将不胜感激。

  var std_obj = {
options:{rows:0,cols:0},
activeEffect:none,
displayMe:function( ){

//'this'指针指向std_obj
if(this.activeEffect ==fade){}

var doSomeEffects =函数(){

//'this'指针指向窗口obj,为什么?
if(this.activeEffect ==fade){}

}

doSomeEffects();
}
};

std_obj.displayMe();


解决方案

/ code>对象实际上是基于你如何进行函数调用。



通常有三种方法可以设置 this object:


  1. someThing.someFunction(arg1,arg2,argN) $ someFunction.call(someThing,arg1,arg2,argN)

  2. someFunction.apply(someThing,[arg1,arg2,argN])

在以上所有示例中, this 对象都是 someThing
调用没有前导父对象的函数通常会得到全局对象,它在大多数浏览器中意味着窗口对象。 p>

I have a question concerning how the "this" pointer is treated in a nested function scenario.

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();

解决方案

In JavaScript the this object is really based on how you make your function calls.

In general there are three ways to setup the this object:

  1. someThing.someFunction(arg1, arg2, argN)
  2. someFunction.call(someThing, arg1, arg2, argN)
  3. someFunction.apply(someThing, [arg1, arg2, argN])

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“this”嵌套函数内的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆