注:颜色标识为重要字眼。
目录:-this详解
-改变this指向的方法
一.this概述
它是JS的关键词,是一个代词“指代不明”,需要代码执行过程中根据上下文判断this的指向。
二.详解
第一种:全局域下this指向window
var a = 0
console.log(this.a);//指向window
第二种:普通函数指向它的调用者,如果没有调用者则默认指向window
function func() {
console.log(this); //this指向window
}
func();
第三种:自执行函数this指向window
(function () {
console.log(this); // this指向window
})();
第四种:对象调用对象函数,谁调用函数this指向谁。
var obj = {
name: '张三',
age: 30,
say: function () {
console.log(this); //下面obj调用了对象中say方法函数,所以this指向obj
var that = this;
}
};
obj.say();
第五种:事件处理函数中, this指向事件源
var box = document.querySelector('.box');
box.onclick = function () {
console.log(this);//this指向事件源box
}
第六种:定时器处理函数, this指向事件源。
setTimeout(function(){
console.log(this);//this指向事件源
},1000)
第七种:构造函数中,this指向实例对象。
要知道构造函数中this蒙上眼睛指也指不到构造函数去.
普通函数之间调用的this指向window;构造函数的调用是通过new关键字,this指向实例对象。
第八种:箭头函数指向箭头函数定义的时候所处的对象,而不是其所使用的时候所处的对象,默认指向父级的this,因为箭头函数没有自己的this,它的this是继承来的,默认指向它定义的时候所处的对象。
三.改变this指向
1.使用变量保存当前的this
2.使用bind()方法改变this指向
3.call()函数改变this
4.apply()函数改变this
5.使用箭头函数改变了事件函数中的this指向
-具体代码解析如下
var time;
var obj1 = {
name: 'LILI',
age: 18,
py: 'Tom',
tc: '唱歌',
xg: '活泼开朗',
say: function () {
console.log('HI,我叫' + this.name); //this指向obj
// 1.使用变量保存当前的this
var that = this;
setTimeout(function () {
console.log('我' + that.age + '岁了');
}, 1000);
},
friend: function () {
setTimeout(function (a,c) {
console.log('我的朋友叫' + this.py + '他喜欢' + a + c);
// 2.使用bind()方法改变this指向
}.bind(this,'跳舞', 1111), 1000);
console.log(time)
},
aihao: function () {
setTimeout(function (b,c) {
console.log('我的爱好' + this.tc + b + c);
// 3.call()函数改变this
}.call(this,'英文歌','五音不全……'), 1000);
},
cha: function () {
setTimeout(function (b,c) {
console.log('我的性格' + this.xg + b + c);
// 4.apply()函数改变this
}.apply(this,['小心翼翼','哈哈哈哈']), 1000);
}
}
obj1.say();
obj1.friend();
obj1.aihao();
obj1.cha();
var func = () => {
console.log(this);
}
func();
// 5.使用箭头函数改变了事件函数中的this指向
box.onclick = () => {
console.log(this);
}
综上:大部分this指向为谁调用就指向谁,全局指向window,但是也有例外,要具体情况具体分析。
欢迎留言纠正!