this的指向性有些复杂,this的指向性取决于函数的调用方式,它的值是在函数调用时所确定的,而非函数声明时。
几种常见的this的指向:
1.全局作用域下的this
// 1. 全局作用域下的this
console.log(this); // this指向window
2.全局作用域下的普通函数this
// 2. 全局作用域下的普通函数this
function Fun() {
console.log(this);
}
Fun() // this指向window
3. 调用对象中的this
(1)以方法的形式调用
person.run是person对象的一个方法,当run方法被直接调用时,this会自动与对象绑定。所以,this指向对象。
var person = {
name: '张三',
run: function () {
console.log(this.name + "正在跑", this) // 张三正在跑
}
}
person.run() // this指向person中的对象
(2)以函数的形式调用
在全局中,声明一个全局变量接收person.run的赋值,这就相当于run1变成了一个独立的函数引用,不再与person对象存在绑定关系。所以这里再次说明:this的指向是取决于函数是如何被调用的。
var person = {
name: '张三',
run: function () {
console.log(this.name + "正在跑", this)
}
}
// person.run() // this指向person中的对象
var run1 = person.run
run1() // 指向window
小结:
当以函数形式调用时,this指向的是window;
当以方法的形式调用时,this指向的是调用方法的对象。
(3)在run里面再增加函数
var person = {
name: '张三',
run: function () {
console.log(this.name + "正在跑", this)
function test() {
console.log(this.name + "正在跑(test)", this) // undefined正在跑(test)
}
test() // this指向window
}
}
person.run() // this指向person中的对象
下面,用一个变量that"承接"run方法中的this指向,让test函数也可以指向person对象,只不过这里不能使用this来指向。
var person = {
name: '张三',
run: function () {
console.log(this.name + "正在跑", this)
var that = this // 用that承接this
function test() {
// console.log(this.name + "正在跑(test)", this)
console.log(that.name+"正在跑(test)","this",this,"that",that) // this指向不变 that指向person对象
}
test() // this指向window
}
}
4.箭头函数中的this
下面的代码为防止看着混淆,我对上方代码进行了部分删除
箭头函数不存在this的指向性问题,它的this指向的是其外部作用域(可以理解为父层)中的this指向。
var person = {
name: '张三',
run: function () {
console.log(this.name + "正在跑", this)
var test1 = ()=>{
/* 箭头函数没有this 指向性问题 用的是其外部作用域(父层)中this的指向 */
console.log(this.name+"正在跑(test1)",this) // this指向person对象
}
test1()
}
}
person.run() // this指向person中的对象
5.构造函数中的this
function Stu(name){
this.name = name
console.log(this)
}
var stu = new Stu("lisi")
使用new来调用函数,该函数就成为了构造函数,其this指向这个新建的对象,即lisi
6.事件中的this
在addEventListener的回调函数中,this指向的是触发事件的对象(这里是div元素本身)
var div = document.querySelector('div')
div.addEventListener('click', function () {
console.log('div', this) // div
function test() {
console.log('div_test', this) // window
}
test()
})
当点击div后,执行结果如下:
总结:
(1)全局作用域下,普通函数的this指向window;
(2)箭头函数没有自己的this指向问题;
(3)this的指向与函数的调用方式有关:
当以函数形式调用时,this指向的是window;
当以方法的形式调用时,this指向的是调用方法的对象。
(4)构造函数的this指向的是其新建对象。
以上是本人在js学习之中对this指向的学习研究,有不足之处请一起探讨学习。