5.1函数中this的指向

函数正常调用时,this指向window

  1. var name="张三"
  2. function show(){
  3. console.log(this.name)
  4. }
  5. function go(){
  6. var name="李四"
  7. console.log(this.name)
  8. }
  9. go();// 张三 window.go();

5.2改变函数内部关键字的指向

如何改变this关键字的指向 call, apply, bind

5.2.1 call 改变函数内部this关键字指向 funName.call(obj)

call,apply调用的时候马上执行

  1. var name="王五";
  2. var obj={
  3. name:"李四"
  4. }
  5. function go(){
  6. console.log(this.name)
  7. }
  8. go();//王五
  9. go.call(obj);//李四

5.2.2apply funName.apply(obj)

  1. var name="王五";
  2. var obj={
  3. name:"李四"
  4. }
  5. function go(){
  6. console.log(this.name)
  7. }
  8. go();//王五
  9. go.apply(obj);//李四

5.2.3 bind

bind** 绑定的函数不会马上执行,只是改变了函数上下文的执行环境**

  1. var name="window"
  2. var meng={
  3. name:"孟"
  4. }
  5. var show=function(a,b){
  6. console.log(this.name);//孟
  7. console.log(a+b);//5
  8. }.bind(meng);
  9. show(2,3);

应用场景

  1. <button id="btn">按钮</button>
  2. <script>
  3. var id="1000";
  4. var btn=document.getElementById("btn")
  5. btn.onclick=function(){
  6. console.log(this.id)//btn
  7. }
  1. <button id="btn">按钮</button>
  2. <script>
  3. var id="1000";
  4. var btn=document.getElementById("btn")
  5. btn.onclick=function(){
  6. window.setTimeout(function(){
  7. console.log(this.id)//1000
  8. },1000)
  9. }

使用bind

  1. var id="1000";
  2. var btn=document.getElementById("btn")
  3. btn.onclick=function(){
  4. window.setTimeout(function(){
  5. console.log(this.id)//btn
  6. }.bind(btn),1000)
  7. }
  8. var id="1000";
  9. var btn=document.getElementById("btn")
  10. btn.onclick=function(){
  11. var self=this;
  12. window.setTimeout(function(){
  13. console.log(this.id)//btn
  14. }.bind(self),1000)
  15. }

使用定时器

  1. var id="1000";
  2. var btn=document.getElementById("btn")
  3. btn.onclick=function(){
  4. setTimeout(()=>{
  5. console.log(this.id)//btn
  6. },1000)
  7. }

call 和apply的区别

应用场景:传递多个参数的情况
call依次去传递
apply 需要传递数组

  1. var name="window"
  2. var meng={
  3. name:"孟"
  4. }
  5. function show(a,b){
  6. console.log(this.name);
  7. console.log(a+b)
  8. }
  9. show(1,2)
  10. show.call(meng,2,3);
  11. show.apply(meng,[2,3])