A. Function.prototype.bind 方法可以改变函数 this 指向。

Function.prototype.bind 方法是 JavaScript 中的一个原生方法,它会创建一个新的函数,并将原函数的 this 指向绑定为 bind 方法的第一个参数。bind 方法的返回值是一个新的函数,调用该新函数时,它的 this 指向被绑定的值。

例如,假设有一个对象 person,其中有一个方法 getName 用于获取姓名:

const person = {
  name: 'Alice',
  getName: function() {
    return this.name;
  }
};

可以使用 bind 方法改变 getName 方法中的 this 指向,将其绑定为 person 对象:

const boundGetName = person.getName.bind(person);
console.log(boundGetName()); // 输出: 'Alice'

在上述代码中,通过 bind 方法将 getName 方法中的 this 指向绑定为 person 对象,然后将返回的新函数赋值给 boundGetName 变量。调用 boundGetName 函数时,它的 this 指向被绑定为 person 对象,因此输出的结果为 'Alice'。

因此,正确答案是 A. Function.prototype.bind。

改变函数 this 指向的方法:Function.prototype.bind

原文地址: https://www.cveoy.top/t/topic/qkzF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录