您当前的位置: 首页 > 

6种函数调用方式的this指向

发布时间:2021-04-11 13:03:58 ,浏览量:3

目录

  • 1、普通函数
  • 2、对象的方法
  • 3、构造函数
  • 4、绑定事件函数
  • 5、定时器函数
  • 6、立即执行函数

1、普通函数

function fun() { console.log('普通函数的this:', this); // 普通函数的this: // Window {window: Window, self: Window,  // document: document, name: "",  // location: Location, …} }; window.fun(); 

2、对象的方法

let objectF = { fun: function() { console.log('对象方法的this:' + this); // 对象方法的this:[object Object] } }; objectF.fun(); 

3、构造函数

function Constructorf() { console.log('构造函数的this:' + this); // 构造函数的this:[object Object] }; // 向构造函数Constructorf的原型上添加func方法 Constructorf.prototype.func = function() { console.log('原型对象的this:' + this); // 原型对象的this:[object Object] }; let constructorF = new Constructorf(); constructorF.func(); 

4、绑定事件函数

let btnThis = document.querySelector('#btnThis'); btnThis.onclick = function() { console.log('绑定事件函数的this:' + this); // 绑定事件函数的this:[object HTMLButtonElement] }; 

5、定时器函数

window.setTimeout(function() { console.log('定时器的this:' + this); // 定时器的 this:[object Window] }, 1000); 

6、立即执行函数

(function() { console.log('立即执行函数的this:' + this); // 立即执行函数的this:[object Window] })(); 
关注
打赏
查看更多评论

暂无认证

  • 3浏览

    0关注

    115983博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录