当前位置:网站首页>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
边栏推荐
- 3D打印Arduino 四轴飞行器
- Understanding and implementation of AVL tree
- Vsync+ triple cache mechanism +choreographer
- Which method is good for the management of fixed assets of small and medium-sized enterprises?
- SDN_ Simple summary
- Shell script echo command escape character
- 【ESP 保姆级教程】疯狂毕设篇 —— 案例:基于阿里云、小程序、Arduino的温湿度监控系统
- 2.3 【pytorch】数据预处理 torchvision.datasets.ImageFolder
- 队列的实现和应用
- Simple load balancing with Nacos
猜你喜欢

MapReduce编程基础

Learning practice: comprehensive application of cycle and branch structure (II)

NiO zero copy

【检测技术课案】简易数显电子秤的设计与制作

2.2 【pytorch】torchvision. transforms

How to solve the problem of fixed assets management and inventory?

Why is the Ltd independent station a Web3.0 website!

Pain points and solutions of equipment management in large factories

计网01-物理层

2.2 【pytorch】torchvision.transforms
随机推荐
Jetson Nano 安装TensorFlow GPU及问题解决
足球篮球体育比赛比分直播平台源码/app开发建设项目
猿人学第20题(题目会不定时更新)
队列的实现和应用
MySQL optimization
Graduation season, I want to tell you
【ESP 保姆级教程 预告】疯狂Node.js服务器篇 ——案例:ESP8266 + MQ系列 + NodeJs本地服务 + MySql存储
小鸟识别APP
LogBack
[interview brush 101] linked list
Daily practice of C language - day 80: currency change
【pytorch学习】torch.device
Promise asynchronous programming
2.2 【pytorch】torchvision. transforms
钓鱼识别app
Installing Oracle EE
Shell script - special variables: shell $, $*, [email protected], $$$
【pytorch】nn. AdaptiveMaxPool2d
js原型陷阱
Principles of Microcomputer - internal and external structure of microprocessor