this指向,认识与理解this指向

this指向

故心故心故心故心小故冲啊



下面从几方面来理解this

1、简单函数

 //简单函数 /this ===window
       function f(){
           console.log(this); //window
       }

2、内置函数

  //内置函数  this ===window
       setInterval(function(){
        console.log(this); //window
       },2000)

3、回调函数

 //回调函数(一个函数被作为参数传递给另一个函数)  this ===window
       function f(callback,v){
            callback(v)
       }
       f(function(v){console.log(this)},'hello'); //this ===window

4、数组

 //数组 this的指向看调用者
       function f(){
        console.log(this);
      };
      var arr = [f,4,5,6];
      arr[0](); //this === arr
      var o =  arr[0];
      o(); //this === window

5、对象

//对象 this的指向看调用者
      function f(){
        console.log(this);
      };
      var obj ={};
      obj.name='xm',
      obj.init=f,
      obj.init();  //obj调用了 所以this就是obj

      //字面量方式对象
      var obj2 = {
          name:'xm2',
          init:f,
      }
      obj2.init(); //obj2调用了 所以this就是obj2

      //构造函数
      function Init(name){
          this.name=name,
          this.action=function(){
            console.log(this);
          }
      }
      var xm = new Init('xm');
      xm.action(); //this === Init{name='xm',action:f}  说明:this 指向的是新创建的对象, 而不是构造函数本身

6、改变对象指向(call apply bind)

 //改变this的指向(apply call bind) apply和call 只是传的参数不一样  apply传的是数组  call直接传
    var a = 10;
    function f(x1, x2) {
        console.log(this.a + " " + x1 + " " + x2)
    }
    var obj = {
        a: 200,
        action: f
    }
    var obj2 = {
        a: 6666,
    }
    
    //1不改变this指向
    obj.action(1, 2)  //200 1 2  this指向的是obj
    //2使用apply改变this指向  
    obj.action.apply(window, [1, 2]) //10 1 2  apply改变this指向为window 所以this指向window
    //3使用call改变this指向  
    obj.action.call(window,1, 2) //10 1 2  call改变this指向为window 所以this指向window
    
    //4使用bind改变this指向  绑定this 也是改变作用域 绑定后不能改变this指向
    var t = obj.action.bind(obj2,1,2); 
    t();  //6666 1 2    
    console.log(t.apply(window, [1, 2]));  //6666 1 2  

总结

this指向谁调用它就指向谁

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值