推荐答案
JavaScript 中 this 的指向取决于函数被调用的方式。其指向大致可分为以下几种情况:
全局上下文: 在全局作用域中(函数体外部),
this通常指向全局对象。在浏览器环境中,全局对象是window;在 Node.js 环境中,全局对象是global。函数上下文:
- 普通函数调用: 在非严格模式下,函数内部的
this指向全局对象(window或global)。在严格模式('use strict';)下,this的值为undefined。 - 箭头函数调用: 箭头函数没有自己的
this,它会捕获其所在上下文的this值,也就是定义时所在作用域的this值。
- 普通函数调用: 在非严格模式下,函数内部的
对象方法: 当函数作为对象的方法被调用时,函数内部的
this指向调用该方法的对象。构造函数: 当使用
new关键字调用函数作为构造函数时,函数内部的this指向新创建的对象实例。
本题详细解读
1. 全局上下文中的 this
在全局作用域(即不在任何函数内部)中,this 指向全局对象。
console.log(this === window); // 在浏览器中输出 true console.log(this === global); // 在 Node.js 中输出 true var a = 10; console.log(this.a); // 输出 10 (在浏览器中,window.a === a)
2. 函数上下文中的 this
2.1 普通函数调用
在普通函数调用时,this 的指向取决于是否处于严格模式。
非严格模式:
function foo() { console.log(this === window); // 在浏览器中输出 true console.log(this); // 输出 window 对象 } foo();严格模式:
function foo() { 'use strict'; console.log(this === undefined); // 输出 true console.log(this); // 输出 undefined } foo();
2.2 箭头函数调用
箭头函数没有自己的 this,它会继承父作用域的 this 值。
// www.javascriptcn.com code example
const obj = {
name: 'object',
func: function() {
console.log(this.name); // 输出 "object"
setTimeout(() => {
console.log(this.name); // 输出 "object", 箭头函数继承了 obj.func 的 this
}, 100);
}
};
obj.func();
function outer() {
this.value = "outer";
const inner = () => {
console.log(this.value) // 输出 "outer"
}
inner()
}
outer();3. 对象方法中的 this
当函数作为对象的方法被调用时,this 指向调用该方法的对象。
// www.javascriptcn.com code example
const obj = {
name: 'MyObject',
sayHello: function() {
console.log(`Hello, I'm ${this.name}`); // 输出 "Hello, I'm MyObject"
console.log(this === obj); // 输出 true
}
};
obj.sayHello();
const anotherObj = {
name: 'anotherObject',
sayHi: obj.sayHello
}
anotherObj.sayHi() //输出 Hello, I'm anotherObject4. 构造函数中的 this
当使用 new 关键字调用函数作为构造函数时,this 指向新创建的对象实例。
function Person(name) {
this.name = name;
console.log(this === p) // 在 new 调用时输出 true
}
const p = new Person('Alice');
console.log(p.name); // 输出 "Alice"
console.log(p instanceof Person); // 输出 true在构造函数中,this 会经历以下步骤:
- 创建一个空对象。
- 将
this指向这个新创建的对象。 - 执行构造函数中的代码,为对象添加属性和方法。
- 如果构造函数没有返回对象,则隐式返回
this指向的新对象;如果返回的是非对象,则忽略返回值,仍然返回新对象,如果返回值是对象,则返回该对象,而不是新对象。