js中this指向的几种情况

箭头函数this指向上级作用域
let obj={
  fn:function(){
   console.log(this)//obj
    return ()=>{
     console.log(this)//obj
    }   
  }
}

var f =()=>{
cosole.log(this)//window
}
f()
在全局作用域,this指向window;this 和window是同一块空间地址;
   console.log(this);// window  
   window.alert()
   this.alert();
给元素的事件绑定的函数中的this,指向了当前被点击的那个元素;
   box.onclick = function () {
        // this : 对象;  
        console.dir(this === box); // 空间地址相同;
        box.style.color = "red";
        this.style.color = "red";
        this = 100;// this 不能放到等号的左边;
    }
看函数执行前有没有".",如果要是没有,那么函数中的this指向window,如果有"." ,那么点前面是谁,this就指向谁;
 function fn() {
        console.log(this);// window  
    }
    fn()
    var fn = function () {
        console.log(this);// window  
    }
    fn();
    var obj = {
        m: 1,
        fn: function () {
            console.log(this);// this就指向了obj;
        }
    }
    var f = obj.fn;
    console.log(f == obj.fn);
    obj.fn();
自执行函数中this 永远指向window;
 (function(){
           console.log(this);// window
     })();
       var obj = {
         fn:(function(){
               console.log(this);// window
              return function(){
                 console.log(this);  
            }
       })()
  }
   var f = obj.fn;
  f();// this ==>window
  let b ={}
   b.f = f
   b.f();// this ==>b
回调函数中的this一般都指向window;
setTimeout(function(){
         console.log(this);//===》window
    },1000);
     var ary=[1,2,3,4]
     
     ary.map(function(){
            console.log(this);//===》window
        })
      function A(){
         console.log(this);  //===》obj
      }
     function B(a){
        var obj = {a:a}
          obj.a();
        }
     B(A)
构造函数中的this指向实例
 function Fun(value) {
        this.aaa = value
        // 这里的this指向的是myfun这个实例对象。
        this.sing = function () {
            console.log(this)//===>myfun
            // 这里的this指向的是:谁调用它,就指向谁。
        }
    }
    const myfun = new Fun('bbb')
    myfun.sing()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值