当前位置:网站首页>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 还是指向函数的实例
边栏推荐
猜你喜欢
随机推荐
The ifconfig compared with IP command
基于 HPSO 与多核 LSSVM 的网络入侵检测
qtcreator调试webkit
js原型和原型链及原型继承
【DB运营管理/开发解决方案】上海道宁为您提供提高工作便利性的集成开发工具——Orange
Summary of Logstash log data write exception troubleshooting
gRPC基础概念:闭包
Some work experience after joining the digital ic design
JVM类加载机制
带你系统学习MySQL索引
维特智能惯导配置
Salesforce解散中国团队,什么样的CRM产品更适合中国人
DOM树的遍历-----修改样式,选择元素,创建和删除节点
ifconfig与ip命令的比较
2022年广东省安全员A证第三批(主要负责人)操作证考试题模拟考试平台操作
Alibaba 最新神作!耗时 182 天肝出来 1015 页分布式全栈手册太香了
多线程之ThreadPoolExecutor
YTU 2418: C语言习题 矩阵元素变换
Section 4-6 of the first week of the second lesson: Appreciation of medical prognosis cases + homework analysis
Pytorch/TensorFlow/Numpy常用函数汇总









