JS中内嵌函数中this关键字的使用

this关键字的使用

 

在嵌套函数中:和变量不同,this关键字没有作用域的限制,在嵌套函数的内部使用this关键字可以分为以下两种情况:

   1)如果嵌套函数作为方法调用,那么this为当前的上下文。

   2)如果当做函数调用,那么this的值依赖于当前使用的是否为严格模式,在非严格模式下,this为全局上下文,否则为undefined.

 

例如:

var test1={

 

      a:1,

      b:2,

      fun1:function(){

             console.log(“fun1: “ +this);    //this为test1对象

             function f(){

                    console.log(“f: “ +this);   //this 为undefined 或者全局对象

             }

      }

}

因此为了能够在函数f中也可以调用上下文的this对象,可以使用通过如下方法解决:

 

例如

var test1={

 

      a:1,

      b:2,

      fun1:function(){

             console.log(“fun1:this : “ +this);    //this为test1对象

             var outer = this;

             function f(){

                   

                    console.log(“f:this: “ +this);   //this 为undefined 或者全局对象

                    console.log(“f:outer: ” +outer);//outer则为外层的对象。 

             }

      }

}

 

这也再次证明了this关键字与作用域的关系。

posted @ 2015-04-17 09:42  aqhjh  阅读(2371)  评论(0编辑  收藏  举报