`
DBear
  • 浏览: 228775 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类

JavaScript精炼——functions中的“this”

阅读更多

      先我们需要知道,function的invoke方式主要有三种:1、单纯调用 2、作为某对象的method被调用 3、apply()和call()调用。针对三种不同的invoke方式,"this"拥有不同的指向:当function被作为单纯的function启动时,那么“this”指向的是global object;当function是某个object的method,并由该object作为方法来启动时,“this”指向调用该function的那个object;使用apply()和call()方法调用时,function中的"this"指向的是这两个方法中的作为第一个参数的那个对象。

 

1. ordinary invoke

var testVar = 20;

function test() {

   var testVar = 40;

   document.write (this.testVar);  // 20 is printed,"this" refers to global object

}

test();  


2. method invoke

var testVar = 20;

function test() {

  var testVar = 30;

  var o = {testVar: 60,

                methodFunc: function(){

     this.testVar = 70;     //when the function invoked, “this” refers to o

       }};

  o.methodFunc();

  document.write(testVar + "<br>");              //print 30

  document.write(o.testVar + "<br>");           //print 70, property of o has been changed

  document.write(this.testVar + "<br>");       //print 20, property of global object remains as


}

test();


3. nested function in a method---ordinary invoke

var testVar = 20;

function test5() {

  var testVar = 30;

  var o = {testVar: 60,

        methodFunc: function(){

                         this.testVar = 70;   

 (function(){

                             this.testVar = 40;

                          })();

 }};

  o.methodFunc();

  document.write(testVar + "<br>");   //30 

  document.write(o.testVar + "<br>");  //70, this refers to object o

  document.write(this.testVar + "<br>"); //40, this refers to global object !!!!Confusing ha? But it's true!!!

}

test5()

 

4. invoked by call() and apply()

function bindedFunc() {

   this.testVar = 40;

}


function test() {

   var testVar = 20;

   var o = {testVar: 30};

   bindedFunc.apply(o);

   document.write(o.testVar) //prints 40

}

test();

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics