当前位置:网站首页>js this丢失问题分析 及 解决方案
js this丢失问题分析 及 解决方案
2022-07-01 09:14:00 【su27_0101】
this丢失案例
var obj = {
name: "Mike",
sayHi: function(){
console.log(this.name + " say Hi !");
}
}
setTimeout(obj.sayHi, 1000);// undefined say Hi
由于函数里的this 永远指向其调用者 1s 后 调用 sayHi 是 window 但window并没有那么属性 所以 为 undefined
解决方案
嵌套一层函数
- setTimeout(function(){obj.sayHi()}, 1000);// undefined say Hi
使用bind修改this指向
- setTimeout(obj.sayHi.bind(obj), 1000);// undefined say Hi
边栏推荐
- TV size and viewing distance
- Shell script - positional parameters (command line parameters)
- [ESP nanny level tutorial preview] crazy node JS server - Case: esp8266 + DHT11 +nodejs local service + MySQL database
- delete和delete[]引发的问题
- [video game training] real topic of 2013 video game of infrared optical communication device
- js原型陷阱
- 闭包实现迭代器效果
- Record a redis timeout
- Daily practice of C language - day 80: currency change
- Jeecg restart alarm 40001
猜你喜欢
FAQ | FAQ for building applications for large screen devices
Principles of Microcomputer - Introduction
Ranking list of domestic databases in February, 2022: oceanbase regained the "three consecutive increases", and gaussdb is expected to achieve the largest increase this month
安装Oracle EE
【pytorch】nn.CrossEntropyLoss() 与 nn.NLLLoss()
Redis——Lettuce连接redis集群
樹結構---二叉樹2非遞歸遍曆
Mise en œuvre simple de l'équilibrage de la charge par nacos
nacos簡易實現負載均衡
Phishing identification app
随机推荐
Shell script - positional parameters (command line parameters)
The jar package embedded with SQLite database is deployed by changing directories on the same machine, and the newly added database records are gone
Jetson Nano 安装TensorFlow GPU及问题解决
毕业季,我想对你说
猿人学第20题(题目会不定时更新)
Performance improvement 2-3 times! The second generation Kunlun core server of Baidu AI Cloud was launched
Bird recognition app
【电赛训练】红外光通信装置 2013年电赛真题
Redis source code learning (29), compressed list learning, ziplist C (II)
Shell脚本-变量的定义、赋值和删除
2.3 [pytorch] data preprocessing torchvision datasets. ImageFolder
Shell script -while loop explanation
Databinding source code analysis
【ESP 保姆级教程 预告】疯狂Node.js服务器篇 ——案例:ESP8266 + DS18B20温度传感器 +NodeJs本地服务+ MySQL数据库
Simple load balancing with Nacos
In the middle of the year, where should fixed asset management go?
LogBack
[ESP nanny level tutorial preview] crazy node JS server - Case: esp8266 + DHT11 +nodejs local service + MySQL database
Why is the Ltd independent station a Web3.0 website!
Ranking list of domestic databases in February, 2022: oceanbase regained the "three consecutive increases", and gaussdb is expected to achieve the largest increase this month