Javascript 指定 `this`225


什么是 `this`在 JavaScript 中,`this` 是一个特殊的关键字,它指向当前执行代码的上下文。它是一个指向当前对象的引用,该对象可以是以下几种类型:
* 全局对象(当在全局上下文中执行代码时)
* 函数对象(当在函数内部执行代码时)
* 方法对象(当在对象的方法内部执行代码时)

如何指定 `this`可以在 JavaScript 中使用以下方法手动指定 `this`:


1. 使用 bind() 方法
`bind()` 方法返回一个新函数,该函数在执行时会将 `this` 绑定到指定的上下文。语法如下:
```
(context)
```
例如:
```js
const obj = {
name: "John"
};
const getName = function() {
return ;
};
const boundGetName = (obj);
(boundGetName()); // 输出:John
```


2. 使用 call() 方法
`call()` 方法直接执行一个函数,并允许将 `this` 指定为第一个参数。语法如下:
```
(context, ...args)
```
例如:
```js
const obj = {
name: "John"
};
const getName = function(arg1, arg2) {
return + " " + arg1 + " " + arg2;
};
((obj, "Doe", "Jr.")); // 输出:John Doe Jr.
```


3. 使用 apply() 方法
`apply()` 方法与 `call()` 方法类似,但它将参数作为数组传递。语法如下:
```
(context, [argArray])
```
例如:
```js
const obj = {
name: "John"
};
const getName = function(args) {
return + " " + args[0] + " " + args[1];
};
((obj, ["Doe", "Jr."])); // 输出:John Doe Jr.
```

使用箭头函数指定 `this`箭头函数(`=>`)不会创建自己的 `this` 绑定,而是从其周围作用域中继承 `this`。这意味着箭头函数中的 `this` 与其定义时的 `this` 相同。
例如:
```js
const obj = {
name: "John",
getName: () => {
return ;
}
};
(()); // 输出:John
```

指定 `this` 的最佳实践指定 `this` 的最佳实践包括:
* 优先使用显式绑定(`bind()`、`call()`、`apply()`)而不是箭头函数。
* 始终注意 `this` 的上下文,尤其是在处理回调函数时。
* 使用 JavaScript 严格模式(`use strict`),它会强制执行显式绑定。

常见问题解答

问:`this` 关键字是否有默认值?
答:是的,`this` 默认为全局对象(在浏览器中为 `window`)。


问:我可以多次使用 bind() 方法吗?
答:是的,你可以将 `bind()` 方法链式调用以创建具有多个绑定的函数。


问:箭头函数中的 `this` 始终等于 undefined 吗?
答:不,箭头函数中的 `this` 继承自其周围作用域的 `this`。

2024-12-13


上一篇:这才是 JavaScript 中 this 关键字的进阶用法

下一篇:JavaScript new 关键字