当前位置:网站首页>为定时器和延时器等其它情况的回调函数绑定当前作用域的this
为定时器和延时器等其它情况的回调函数绑定当前作用域的this
2022-07-01 18:46:00 【王元肉】
前置场景
mounted() {
console.log("this",this);
setTimeout(function() {
console.log("init",this);
},1000);
},

想在延时器的回调函数中访问当前Vue实例怎么办?
方式1 额外变量(不推荐)
mounted() {
console.log("this",this);
const that = this;
setTimeout(function() {
console.log("init",that);
},1000);
}

创建了多余的变量,不推荐使用。
方式2 箭头函数
mounted() {
console.log("this",this);
setTimeout(
()=>{
console.log("箭头函数",this);
},
1000
);
},

使用箭头函数,this是父作用域中的this,当时与此同时箭头函数中arguments也是父作用域中arguments。
方式3 使用bind
mounted() {
console.log("this",this);
setTimeout(function () {
console.log("bind",this);
}.bind(this),1000)
},

边栏推荐
猜你喜欢

数字化转型企业成功的关键,用数据创造价值

The key to the success of digital transformation enterprises is to create value with data

Actual combat of flutter - fast implementation of audio and video call application

Regular expression =regex=regular expression

【无标题】

再回顾集合容器

Cookie和Session的相关概念

Basic use of MySQL

Audio and video, encoding and decoding related e-books, gadgets, packaged for free!

A brief understanding of white box encryption technology
随机推荐
【无标题】
ddr4测试-2
H264 encoding profile & level control
How to correctly use vertx to operate redis (3.9.4 with source code analysis)
商业智能BI开发和报表开发有什么本质区别?
HLS4ML报错The board_part definition was not found for tul.com.tw:pynq-z2:part0:1.0.
【sql优化】with as 和 临时表的区别
DTD modeling
[untitled]
直播HLS协议
Anaconda安装虚拟环境到指定路径
Shell advanced
Native JS creates a calendar - supports mouse wheel scrolling to select months - and can be ported to any framework
使用 Kibana Timelion 进行时间序列分析
Wireshark packet analysis TCP, FTP
1592 例题1 国王(Sgu223 LOJ10170 LUOGU1896 提高+/省选-) 暴力思考 状压DP 01背包
Introduction and installation of crunch, and making password dictionary with crunch
安装sharp报错
Why must we move from Devops to bizdevops?
HLS4ML进入方法