返回
ES5和ES6的this的异同
前端
2024-02-11 18:40:06
前言
this是JavaScript中一个非常重要的概念,它在很多地方都会用到,比如对象的方法、函数的调用、事件处理函数等。在不同的情况下,this的值可能会不同。这篇文章将对javascript(包括ES3、ES5、ES6)中的this问题进行整理,希望能对读者有所帮助。
ES3、ES5和ES6中this的异同
ES3和ES5中this的用法
在ES3和ES5中,this的值由函数的调用方式决定。如果一个函数是作为对象的方法被调用的,那么this的值就是该对象。如果一个函数不是作为对象的方法被调用的,那么this的值就是global对象(在浏览器中,global对象就是window对象)。
// 作为对象的方法调用
const person = {
name: "John",
age: 20,
greet: function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
};
person.greet(); // Hello, my name is John and I am 20 years old.
// 不是作为对象的方法调用
function greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
greet(); // TypeError: Cannot read properties of undefined (reading 'name')
ES6中this的用法
在ES6中,箭头函数的this值是固定的,它是由箭头函数所在的作用域决定的。也就是说,箭头函数的this值与它的调用方式无关。
// 作为对象的方法调用
const person = {
name: "John",
age: 20,
greet: () => {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
};
person.greet(); // TypeError: Cannot read properties of undefined (reading 'name')
// 不是作为对象的方法调用
const greet = () => {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
greet(); // TypeError: Cannot read properties of undefined (reading 'name')
箭头函数与其他函数的this区别
箭头函数与其他函数在this值上的区别主要体现在以下几个方面:
- 箭头函数的this值是固定的,它是由箭头函数所在的作用域决定的。
- 箭头函数不能作为构造函数使用。
- 箭头函数不能使用arguments对象。
- 箭头函数不能使用yield。
结语
this是JavaScript中一个非常重要的概念,它在很多地方都会用到。在不同的情况下,this的值可能会不同。ES3和ES5中this的值由函数的调用方式决定。在ES6中,箭头函数的this值是固定的,它是由箭头函数所在的作用域决定的。箭头函数与其他函数在this值上的区别主要体现在以下几个方面:箭头函数的this值是固定的,它是由箭头函数所在的作用域决定的;箭头函数不能作为构造函数使用;箭头函数不能使用arguments对象;箭头函数不能使用yield关键字。