首先,提出的问题根本不包含this,这很有趣,因为它是所提供问题的一个神奇例外。
JavaScript 是词法范围的。也就是说,函数可以访问它们定义的范围,而不是访问当前堆栈任意位置的值。
const rememberX = (x) => () => x;
// a function that takes a value and returns a function
// when the inner function is called, it returns the value
let x = 5;
let x42 = rememberX(42);
let x10 = rememberX(10);
x = 20;
x42(); // 42
x10(); // 10
词法作用域提供了闭包的概念,这就是上述工作的原因。这使得它不像传统环境中的其他语言,而更像是一种函数式编程语言。
有趣的是,this 是打破这种模式的唯一值。它非常晚绑定,并在执行时确定。
class Person {
constructor (name) {
this.type = "person";
this.name = name;
}
sayHi () {
console.log(`${this.name}, the ${this.type}, says “Hi”.`);
}
}
const bob = new Person("Bob");
bob.sayHi(); // "Bob, the person, says “Hi”."
const spot = {
type: "dog",
name: "Spot",
sayHi: bob.sayHi
};
spot.sayHi(); // "Spot, the dog, says “Hi”."
bob.sayHi.apply({
type: "ape",
name: "Grape"
}); // "Grape, the ape, says “Hi”."
// apply is a method that all functions have,
// which sets `this` for this invocation
const bind = function (method, overriddenThis) {
return function (...args) {
return method.apply(overriddenThis, args);
};
};
// bind also exists as a method on functions,
// to prevent `this` from being overwritten, using closure
const sayHi = bind(bob.sayHi, bob);
sayHi.apply(spot); // "Bob, the person, says “Hi”."
因此,您的基于堆栈的调用无法按预期工作是有原因的,为什么this 与您的预期不同,以及如何处理它。