Context 上下文
在 JavaScript 中,有三个上下文需要关注:
- 函数上下文
- 类上下文
- 全局上下文
this
JavaScript 中的 this 关键字指的是函数所属的对象,或者当前执行函数的对象。在大多数情况下,this 的值取决于函数的调用方式。
在函数中
function showThis() {
  console.log(this);
}
// 在这种情况下,'this' 指向全局对象
showThis();
在对象方法中
const myObject = {
  property: "I'm a property",
  method: function () {
    console.log(this.property);
  }
};
// 方法内部的 'this' 指向当前对象(即 myObject)
myObject.method();
bind
JavaScript 中的 bind() 方法用于创建一个新函数,当调用时,其 this 关键字被设置为提供的参数值。它通常用于显式设置函数的上下文。
const m = {
  x: 42,
  getX: function () {
    return this.x;
  },
};
const unboundGetX = m.getX;
// 函数在全局范围内被调用
console.log(unboundGetX());
// 期望输出:undefined
const boundGetX = unboundGetX.bind(m);
console.log(boundGetX());
// 期望输出:42
bind() 函数创建一个新的绑定函数。调用绑定函数通常会触发执行它包装的函数,即目标函数。
apply
JavaScript 中的 apply() 方法用于使用给定的 this 值以及数组或类数组对象参数调用函数。
// 定义一个使用 'this' 的函数
function greet(age) {
  console.log(`Hello, ${this.name}! You are ${age} years old.`);
}
// 创建一个用作 'this' 值的对象
const person = {
  name: 'John',
  age: 30
};
// 使用 apply() 调用 greet 函数,将 person 对象作为 'this',
// 并传递一个数组作为参数
greet.apply(person, [25]);
代码挑战
尝试实现
bind()方法的简化版本。创建一个名为customBind的函数,模仿bind()的行为。
customBind函数应该接受两个参数:
- 用于设置成
this的对象。- 被调的目标函数。
customBind函数应返回一个新函数,其被调用时需使用给定的上下文。注意:可使用
...args语法来捕获传递给新函数的任意参数。
Loading...
> 此处输出代码运行结果