「这是我参与2022首次更文挑战的第5天,活动详情查看:2022首次更文挑战」。
this关键字在JavaScript进阶知识中大家关注的相对较少,虽然关注的少,平时用到的地方还是非常多的。
介绍
在 JavaScript 中,this关键字是指当前正在执行代码的对象。
简单解释如下:
- 默认情况下,
this指的是全局对象。 - 在函数中,当不处于严格模式时,
this指的是全局对象。 - 在函数中,当处于严格模式时,
this是undefined. - 在箭头函数中,
this保留封闭词法上下文的值this。 - 在对象方法中,
this指的是调用该方法的对象。 - 在构造函数调用中,
this绑定到正在构造的新对象。 - 在事件处理程序中,
this绑定到放置侦听器的元素。
1. 全局对象
无论是否在严格模式下,在全局执行环境中(在任何函数体外部)this 都指向全局对象。
// 在浏览器中, window 对象同时也是全局对象:
console.log(this === window); // true
a = 666;
console.log(window.a); // 666
this.b = "777";
console.log(window.b) // "777"
console.log(b) // "777"
2. this 内部函数
在函数内部,this的值取决于函数被调用的方式。
因为下面的代码不在严格模式下,而且 this 的值不是由该调用设置的,所以 this 的值默认指向全局对象,浏览器中就是 window。
//非严格模式
function f1(){
return this;
}
//在浏览器中:
f1() === window; //在浏览器中,全局对象是window
//在node中:
f1() === globalThis;
在严格模式下,如果进入执行环境时没有设置 this 的值,this 会保持为 undefined,如下:
//严格模式
function f2(){
"use strict";
return this;
}
f2() === undefined; // true
3. 对象方法
当函数作为this对象的方法被调用时,指的是调用该方法的对象。这适用于对象原型链中任何地方定义的方法(即自己的和继承的方法)。
let obj = {
f: function() {
return this;
}
};
const myObj = Object.create(obj);
myObj.foo = 1;
console.log(myObj.f()); // { foo: 1 }
- 对象构造函数
4. this内部构造函数
在 JavaScript 中,构造函数用于创建对象。当函数用作构造函数时,this指的是在其中使用它的对象。
示例:
function User() {
this.name = '小王';
console.log(this); //User {name: "小王"}
}
let user1 = new User();
console.log(user1.name); //小王
this指向的是 user1.
注意:当this与ES6 类一起使用时,它指的是在其中使用它的对象(类似于构造函数)。
5. this 内箭头函数
在箭头函数内部,this指的是父作用域。示例:
const print = () => {
console.log(this);
}
print(); // Window {...}
箭头函数没有自己的this. 当this在箭头函数内部使用时,this指的是它的父作用域对象。示例,
const user = {
name: '小王',
sayHi () {
let hi = () => console.log(this.name);
hi();
}
}
user.sayHi(); // 小王
函数this.name内部hi()指的是user对象。
当箭头函数与 一起使用时this,它指的是外部作用域。
6. 事件处理程序
在事件处理程序中使用时,this指的是放置侦听器的元素。
示例:
const el = document.getElementById('my-el');
el.addEventListener('click', function() {
console.log(this === el); // true
});
7. this绑定
使用 Function.prototype.bind()从现有函数返回一个新函数,其中this永久绑定到 的第一个参数bind()。
示例:
function f() {
return this.foo;
}
var x = f.bind({foo: 'hello'});
console.log(x()); // 'hello'
类似地,使用
Function.prototype.call()orFunction.prototype.apply()会将被调用函数绑定this到这些函数中的任何一个的第一个参数,仅用于此调用。
function f() {
return this.foo;
}
console.log(f.call({foo: 'hi'})); // 'hi'