当前位置:网站首页>this指向问题
this指向问题
2022-08-02 03:35:00 【呦呦鹿鸣[email protected]】
this 是指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,一般情况下this的最终指向是调用它的对象
1、全局作用域或者普通函数中this指向窗口顶级对象window(注意定时器里面this指向window)
console.log('全局:',this);
function demo(){
console.log('demo:',this);//window
// 这里的函数 其实也是再全局下调用的 相当于window.demo() 所以打印的结果还是window
}
demo();
window.setTimeout(funtion() {
console.log(this);
},1000)2、 对象里面的this指向
var person = {
realname:'张三',
age:20,
say:function(){
console.log('说话');
console.log(this);//指向的是当前对象本身 person
}
};
console.log(person.realname);
person.say();3、构造函数里面的this指向问题
function Person(realname,age){
this.realname = realname;
this.age = age;
this.say = function(){
console.log('说话');
console.log(this);//构造函数里面的this 指向的是实例化的这个对象
// 实例化指的是 new出来的实例
}
}
var p1 = new Person('李四',22);
var p2 = new Person('王武',23);
p1.say();
p2.say();4、在定时器里面的this指向
var btn= document.querySelector('#btn');
btn.onclick = function(){
console.log(this);//btn对象
setTimeout(function(){
console.log(this);//定时器 是window调用的 所以这里打印的是window
},1000)
}5、案列中的this指向
<input type="number">
<button>发送</button>
<script>
var btn=document.querySelector('button');
var time=3;
btn.addEventListener('click',function(){
btn.disabled=true;//可以修改成this.disabled=true;其指向的是btn
var timer=setInterval(function(){
if(time==0){
clearInterval(timer);
btn.disabled=false;//不可修改this指向,其函数指向的是定时器函数(即window对象),不是btn对象下的函数
btn.innerHTML='发送'
}else{
btn.innerHTML='还剩下'+time+'秒';
time--;
}
},1000);
})
</script>版权声明
本文为[呦呦鹿鸣[email protected]]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_53841687/article/details/125540120
边栏推荐
猜你喜欢
随机推荐
Promise
网络安全nvr,用于对接电网B接口(国网B接口)视频监控系统B接口
Plus版SBOM:流水线物料清单PBOM
rtsp转flv
音视频文件的码率与大小计算
计算属性的学习
Hash table problem solving method
js平层数组转树形结构(解决数据处理后源数据篡改)
剑指Offer 33.二叉搜索树的后序遍历序列
【LeetCode】Sum
JPA自定义SQL Column ××× not found.
Process (in): process state, process address space
Liunx服务环境部署
h264转hls
【LeetCode】合并
QT中更换OPENCV版本(3->4),以及一些宏定义的改变
STM32 CAN 介绍以及相关配置
unity 代码拆分图集
Mongoose无法更新时间戳
运行时应用自我保护(RASP):应用安全的自我修养









