在 JavaScript 中,若要保持方法传递时的作用域,可以使用 bind() 方法。bind() 方法创建一个新的函数,其 this 关键字设置为调用 bind() 方法时传递的值。下面是一个例子:
function Person(name) {
this.name = name;
this.sayName = function() {
console.log('My name is ' + this.name);
}
}
var person1 = new Person('Alice');
var person2 = new Person('Bob');
function sayHello(greeting) {
greeting();
}
sayHello(person1.sayName.bind(person1)); // 输出 "My name is Alice"
sayHello(person2.sayName.bind(person2)); // 输出 "My name is Bob"
在上面的例子中,我们创建了一个名为 Person 的构造函数,并在其原型上定义了一个名为 sayName 的方法。我们还定义了一个名为 sayHello 的函数,该函数接受一个函数参数并将其作为 greeting 变量输入。最后,我们通过调用 sayHello 函数并传递绑定到 person1.sayName 和 person2.sayName 的方法,来测试 bind() 的工作方式。