当前位置:网站首页>为定时器和延时器等其它情况的回调函数绑定当前作用域的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)
},

边栏推荐
- ffmpeg AVFrame 转 cv::Mat
- wireshark报文分析tcp,ftp
- Ffmpeg error code
- 新窗口打开页面-window.open
- Collation of open source protocols of open source frameworks commonly used in Web Development
- servlet知识点
- What is the essential difference between Bi development and report development?
- What must be done in graduation season before going to Shanhai
- 利用win7漏洞进行系统登录密码破解
- Actual combat of flutter - fast implementation of audio and video call application
猜你喜欢

类加载机制

HLS4ML进入方法

JS的Proxy

Introduction to relevant processes and functions of wechat official account development

Instagram 为何从内容共享平台变成营销工具?独立站卖家如何利用该工具?

Optimization of video streaming with repeated requests in the case of unstable easygbs network

Basic use of MySQL

MySQl的基本使用

How to solve the problem of splash screen when the main and sub code streams of easygbs are h.265?

118. 杨辉三角
随机推荐
Linux下安装Redis,并配置环境
Werewolf killing strategy: do you think I'm easy to cheat? Who do we believe!
GB28181之SIP协议
Learning records of building thingsboard, an Internet of things platform
OpenCV视频质量诊断----视频遮挡诊断
使用 Kibana Timelion 进行时间序列分析
118. Yanghui triangle
Mysql查询结果去除换行
[Mori city] random talk on GIS data (I)
Bao, what if the O & M 100+ server is a headache? Use Xingyun housekeeper!
Nat penetration of gb28181
【AI服务器搭建】CUDA环境
Native JS creates a calendar - supports mouse wheel scrolling to select months - and can be ported to any framework
Live HLS protocol
P2433 [deep foundation 1-2] primary school mathematics n in one
Proxy in ES6
PowerDesigner设计Name和Comment 替换
Salesmartly has some tricks for Facebook chat!
torch.nn.functional.interpolate函数
ffmpeg 音频相关命令