返回
this 的坑爬出来了吗?你爬了吗?
前端
2023-10-21 04:32:39
JavaScript中的this
this是JavaScript语言中的一个保留,用来表示函数运行时自动生成的一个内部对象,只能在函数内部使用。this的指向总是指向调用该函数的对象,如果没有调用对象,那么this指向window对象。
this的指向
1. 函数调用
当函数作为普通函数调用时,this指向window对象。
function foo() {
console.log(this); // window
}
foo();
2. 对象方法调用
当函数作为对象的方法调用时,this指向调用该方法的对象。
const obj = {
name: '张三',
sayName() {
console.log(this.name); // 张三
}
};
obj.sayName();
3. 构造函数调用
当函数作为构造函数调用时,this指向新创建的对象。
function Person(name) {
this.name = name;
}
const person = new Person('张三');
console.log(person.name); // 张三
this的用法
1. 访问对象属性和方法
可以通过this来访问对象属性和方法。
const obj = {
name: '张三',
sayName() {
console.log(this.name); // 张三
}
};
obj.sayName();
2. 调用其他函数
可以通过this来调用其他函数。
const obj = {
name: '张三',
sayName() {
function innerFoo() {
console.log(this.name); // 张三
}
innerFoo();
}
};
obj.sayName();
3. 作为参数传递
可以通过this作为参数传递给其他函数。
function foo(obj) {
console.log(obj.name); // 张三
}
const obj = {
name: '张三'
};
foo(obj);
this的坑
1. 箭头函数中的this
箭头函数没有自己的this,它的this指向外层函数的this。
const obj = {
name: '张三',
sayName: () => {
console.log(this.name); // undefined
}
};
obj.sayName();
2. bind、call和apply
bind、call和apply都可以改变函数的this指向。
const obj = {
name: '张三'
};
function foo() {
console.log(this.name); // 张三
}
const boundFoo = foo.bind(obj);
boundFoo(); // 张三
3. 构造函数中的this
构造函数中的this指向新创建的对象,但是如果忘记使用new关键字调用构造函数,那么this指向window对象。
function Person(name) {
this.name = name;
}
const person = Person('张三');
console.log(person); // undefined
总结
this是JavaScript中一个很重要的概念,它指向函数运行时自动生成的一个内部对象,它只能在函数内部使用。this的指向总是指向调用该函数的对象,如果没有调用对象,那么this指向window对象。在使用this时需要注意箭头函数中的this、bind、call和apply、构造函数中的this等问题。