当前位置:网站首页>this指向问题
this指向问题
2022-08-08 06:21:00 【Youser511】
函数的不同调用方式决定了this的指向不同
1:普通函数 this指向window
var a = 4;
function fn(){
console.log("普通函数的this" + this);
}
// window.fn()
// console.log(window)
2:对象的方法 this指向的是对象o
var o = {
sayHi:function(){
console.log("对象的方法this" + this)
}
}
// o.sayHi()
3:构造函数this指向 构造函数的实例对象
原型对象里面的this 指向的也是实例对象
function Star(){
}
Star.prototype.sing = function(){
}
var s = new Star()
4:绑定事件函数 this指向的是函数的调用者
var btn = document.querySelector('button');
btn.onclick = function(){
console.log(this); // btn
}
5:定时器函数 this指向的也是window
window.setTimeout(function(){
console.log(this,"定时器函数")//window
},1000);
6:立即执行函数 this还是指向window
(function() {
console.log("立即执行函数" + this);//window
})();
7:箭头函数 this指向的是箭头函数所在的环境的
箭头函数体内的this对象,就是定义该函数时所在的作用域指向的对象,而不是使用时所在的作用域指向的对象。
var btn = document.querySelector('button');
btn.onclick = function(){
window.setTimeout(()=>{
console.log(this,"定时器函数")//btn
},1000);
}
btn.onclick = ()=>{
console.log(this);//window
}
配合改变this指向食用
边栏推荐
猜你喜欢
随机推荐
李沐老师 PyTorch版——线性回归 + softmax回归的简洁实现(3)
oracle insert sql error
C face recognition
APISIX Ingress v1.5-rc1 released
学习go语言,你要遵循什么样的学习路径才能学明白?
Docker安装nacos2.0并指定mysql,安装sentinel
ValueError: Length of feature_names, 4 does not match number of features, 2 的解决方法
YoloV4训练自己的数据集(四)
Stream API
测试与调试
YoloV4训练自己的数据集(五)
docker安装Mysql和其数据持久化
ffmpeg获取视频时长和分辨率
LLVM系列第二十九章:写一个简单的常量加法“消除”工具(Pass)
from sklearn import cross_validation 报错的解决方法
chmod +x 的含义,为什么要chmod +x
C人脸识别
探索数字安全中国方案
使用C语言实现Hailstone序列
【ESP8266】ESP12S/12F 最小系统设计及typeC自动下载电路设计









