JavaScript中的各种函数以及this指向

1、普通函数

this指向window对象

function fn(){
      console.log(this);  // Window
    }
fn()

2、对象中的方法

this指向该方法的所属对象

const obj = {
      say:function(){
        console.log(this);  //{say: ƒ}
      }
    }
obj.say()

3、构造函数

this指向构造函数的实例化对象(原型上的方法同样如此)

 function Person(){
      Person.prototype.say = function(){
        console.log(this);    // Person {}
      }
    }
 const hzy =new Person()
 hzy.say()

4、绑定事件函数

this指向事件绑定的对象

const btn = document.querySelector('button');
btn.onclick = function(){
       console.log(this);  // <button>123</button>
} 

 5、定时器函数

this指向window对象

setTimeout(() => {
      console.log(this);  // // Window
}, 1000);

6、立即执行函数

this指向window对象

(function(){
      console.log(this); // window
})()

7、箭头函数

箭头函数没有自己this指向,里面的this指向外层作用域(如果箭头函数外层有函数,那么外层函数的this就是箭头函数的this,如果没有,则this指向window)

//箭头函数外层没有函数
let sum = (x,y)=>{
      console.log(this);  //Window
      return x + y;
    }
sum(1,2)
//箭头函数外层有函数
 const btn = document.querySelector('button');
   btn.onclick = function () {
     let sum = (x, y) => {
        console.log(this);  //this指向btn
        return x + y;
     }
     sum(1, 2)
  }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值