当前位置:网站首页>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
边栏推荐
- 序列化、监听、自定义注解
- Pain points and solutions of equipment management in large factories
- 樹結構---二叉樹2非遞歸遍曆
- PR training notes
- js valueOf 与 toString 区别
- TV size and viewing distance
- laravel postman 提交表单出现419错误。2020年7月6日记。
- Record a redis timeout
- 【ESP 保姆级教程】疯狂毕设篇 —— 案例:基于物联网的GY906红外测温门禁刷卡系统
- How to launch circle of friends marketing and wechat group activities
猜你喜欢
Jeecg restart alarm 40001
2.3 【kaggle数据集 - dog breed 举例】数据预处理、重写Dataset、DataLoader读取数据
nacos简易实现负载均衡
Reproduced Xray - cve-2017-7921 (unauthorized access by Hikvision)
NiO zero copy
猿人学第20题(题目会不定时更新)
Microcomputer principle - bus and its formation
小鸟识别APP
2.3 [pytorch] data preprocessing torchvision datasets. ImageFolder
Learning practice: comprehensive application of cycle and branch structure (II)
随机推荐
Flink面试题
如何高效拉齐团队认知
Shell script - definition, assignment and deletion of variables
Promise异步编程
Principles of Microcomputer - internal and external structure of microprocessor
The jar package embedded with SQLite database is deployed by changing directories on the same machine, and the newly added database records are gone
通过 代码实例 理解 浅复制 与 深复制
2.3 【pytorch】数据预处理 torchvision.datasets.ImageFolder
TV size and viewing distance
Latex插入的eps图片模糊解决方法
JCL and slf4j
Flink interview questions
Mysql8.0 learning record 17 -create table
Principle and application of single chip microcomputer timer, serial communication and interrupt system
I use flask to write the website "one"
Shell script - positional parameters (command line parameters)
js原型继承仅可继承实例而非构造器
Day06 branch structure and cycle (III)
phpexcel 里 获取某一列的列表 获取某一列的字母
Implementation and application of queue