this

2017-01-17  本文已影响27人  ahong_吴

通俗点说:就是执行一个函数,然后把this和参数传进去。fun.call(this,参数1,参数2,参数...)

var john = { 
  firstName: "John" 
}
function func() { 
  alert(this.firstName + ": hi!")
}
john.sayHi = func
john.sayHi() 

输出 john:hi!

  func() 

  function func() { 
    alert(this)
  }

输出:window 因为是window调用的func函数

     function fn0(){
         function fn(){
           console.log(this);
         }
       fn();
     }

   fn0();

   document.addEventListener('click', function(e){
     console.log(this);
     setTimeout(function(){
         console.log(this);
     }, 200);
}, false);

输出 window document window

var john = { 
  firstName: "John" 
}

  function func() { 
    alert( this.firstName )
}
func.call(john) 

输出 john 因为利用了call this变成了john

var john = { 
  firstName: "John",
  surname: "Smith"
}

 function func(a, b) { 
  alert( this[a] + ' ' + this[b] )
}
func.call(john, 'firstName', 'surname') 

输出 john smith

var module= {
// var me = this;   //修改
  bind: function(){
    $btn.on('click', function(){
      console.log(this) //this指什么 $btn
      //me.showMsg();
    })
  },
  
  showMsg: function(){
    console.log('ahong');
  }
}
上一篇 下一篇

猜你喜欢

热点阅读