当前位置:网站首页>js中的this问题
js中的this问题
2022-08-11 02:42:00 【糊涂不是傻】
问题1
$("#ad").click(function(){
setTimeout(function(){
console.log(this);
this.style.background = "pink";
} ,2000);
})
此时达不到把id为ad的元素背景色置为粉色。因为this指向window。
1、函数里面的this都指向window。
更改方法
$("#ad").click(function(){
let that = this;
setTimeout(function(){
console.log(this);
that.style.background = "pink";
} ,2000);
})
1)用参数记录外层this的值。
$("#ad").click(function(){
setTimeout(()=>{
console.log(this);
this.style.background = "pink";
},2000)
})
2)箭头函数的this为静态。
2、以方法的形式调用时,this 是调用方法的对象
3、以构造函数的形式调用时,this 是新创建的那个对象
4、使用 call 和 apply 调用时,this 是指定的那个对象
5、箭头函数:箭头函数的 this 看外层是否有函数 如果有,外层函数的 this 就是内部箭头函数的 this 如果没有,就是 window
6、特殊情况:通常意义上 this 指针指向为最后调用它的对象。这里需要注意的一点就是 如果返回值是一个对象,那么 this 指向的就是那个返回的对象,如果返回值不是一个对象那么 this 还是指向函数的实例
边栏推荐
- Some work experience after joining the digital ic design
- comp3331-9331-21t2-midterm复习
- Mysql_Note3
- 对加密世界的经济误解:现金是储蓄?稀缺性创造价值?
- 英伟达 GPU 架构简史
- BUU brushing record
- gRPC闭包调度器
- Section 4-6 of the first week of the second lesson: Appreciation of medical prognosis cases + homework analysis
- 全局大喇叭--广播机制
- WeChat public account background management
猜你喜欢
随机推荐
多线程之ThreadPoolExecutor
[机缘参悟-66]:怎样才能让别人愿意帮你:利益共享法则、“大道”、“人性”
comp3331-9331-21t1-midterm复习
深度学习中的模型设计
MySQL的主从复制+读写分离+分库分表,看这一篇文章就够了
ES6进阶 字符串处理新特性
[Detailed explanation of C data storage] (1) - in-depth analysis of the storage of shaping data in memory
comp3331-9331-22t1-midterm复习辅导-tutorial week 5
Research on the Application of Privacy Computing Fusion
WeChat public account background management
OpenCV founder: Open source must not be completely free!
BUU刷题记录
求和、计数的窗口函数应用
YTU 2418: C语言习题 矩阵元素变换
MySQL八股文背诵版(续)
压力能变成动力
GBJ3510-ASEMI家电电源用整流桥GBJ3510
Gaussian beam focused by thermal lens
Ninjutsu_v3_08_2020-安全渗透系统安装
leetcode:358. K 距离间隔重排字符串









