JavaScript_this
1. 基本概念
“this” 是 JavaScript 中一个非常重要且有时容易混淆的关键字。简单来说,this 的值是在函数被调用时决定的,而不是在函数定义时决定的。它取决于函数的调用位置和方式,可以指向不同的对象。
- 1)在全局作用域中,
this指向全局对象(在浏览器中为window)。 - 2)在对象方法中,
this指向调用方法的对象。 - 3)在构造函数中,
this指向新创建的实例对象。 - 4)在事件处理函数中,
this指向绑定事件的 DOM 元素。 - 5)在箭头函数中,
this是词法绑定的,它与包围它的非箭头函数的this值相同。
1.1 常见情境
全局作用域:
在非严格模式下,全局范围内的
this默认指向全局对象window。javascriptconsole.log(this === window); // true函数调用:
直接调用一个函数(非严格模式),
this指向全局对象window。javascriptfunction myFunction() { console.log(this); // window } myFunction();对象方法调用:
当函数作为对象的方法被调用时,
this指向该对象。javascriptconst obj = { name: "Alice", getName: function() { console.log(this.name); // Alice } }; obj.getName();构造函数调用:
在构造函数中,
this指向新创建的实例对象。javascriptfunction Person(name) { this.name = name; } const person = new Person("Bob"); console.log(person.name); // Bob事件处理函数:
在事件处理函数中,
this指向绑定事件的 DOM 元素。javascriptconst button = document.createElement('button'); button.addEventListener('click', function() { console.log(this); // <button> element });箭头函数:
箭头函数不会创建自己的
this,它会捕获其所在上下文的this值。javascriptconst obj = { name: "Charlie", getName: function() { const arrowFunc = () => console.log(this.name); arrowFunc(); // Charlie } }; obj.getName();严格模式("use strict"):
在严格模式下,顶级上下文中的
this是undefined,而不是window。javascript"use strict"; function myStrictFunction() { console.log(this); // undefined } myStrictFunction();显式绑定:
使用
call、apply、bind可以显式绑定this。javascriptfunction greet() { console.log(this.name); } const john = { name: "John" }; greet.call(john); // John