JavaScript精炼——functions中的“this”

原文链接:http://dbear.iteye.com/blog/609090

------------------------------------------------------------------------

   先我们需要知道,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();


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值