JS中的this指向问题
this的指向问题
全局作用域
在JS中,全局的变量和函数附着在
global
对象上,全局对象在浏览器环境下是
window
对象。
- 在全局作用域中,
指向全局对象this
。window
console.log(this); // window对象
console.log(window); // window对象
console.log(this === window); // true
var a = 3;
console.log(a); // 3
console.log(window.a); // 3
console.log(this.a); // 3
console.log(a === window.a && window.a === this.a); // true
function say(){
console.log("hi");
}
this.say(); // hi
全局变量和window对象的关系
- 使用
声明定义的全局变量会被挂载到全局对象var
上。window
- 使用
、let
声明定义的全局变量不会被挂载到全局对象const
上。window
普通函数
普通函数内部的
this
指向调用这个函数的对象。
案例1
function testThis(){
console.log(this);
}
testThis(); // 输出结果: window对象
在全局作用域中被调用,相当于执行了
testThis()
,则函数被调用时,内部的
window.testThis();
指向
this
.
window
案例2
var obj = {
test(){
console.log(this);
}
}
obj.test(); // obj
普通函数作为对象上的方法时, this
指向调用方法的对象.
案例3
var obj = {
test1(){
console.log(this);
},
test2(){
test(); // 这里相当于执行了window.test();
}
}
function test(){
console.log(this);
}
obj.test1(); // obj
obj.test2(); // window
test(); // window
构造函数
构造函数一般是通过
new
关键字调用的,其内部的
this
指向新创建的对象。
function Person(name,age){
this.name = name;
this.age = age;
console.log(this);
}
const person1 = new Person('张三',20);
const person2 = new Person('李四',18);
构造函数利用指向新对象的,将传入的
this
和
name
属性直接赋值给新对象。通过最后的
age
语句也可以检测出
console.log(this)
的指向。
this
绑定事件函数
const btn = document.querySelector('button');
btn.onclick = function(){
console.log(this);
}
此处,点击事件触发时,
-
指向触发该事件的对象。
this
指向按钮这个
this
对象。
DOM
箭头函数
箭头函数没有属于自己的
this
。因此,箭头函数内部使用的
this
就是箭头函数所在上下文的
this
.
var obj = {
test1(){
console.log(this);
},
test2:()=>{
console.log(this);
}
}
obj.test1(); // obj
obj.test2(); // window
是箭头函数,没有属于自己的
test2
。在其内部输出的
this
是
this
所在上下文的
obj
,即
this
。
window
改变this指向的方法
函数是对象,有属于自己的属性和方法。