我遇到了一个无法解决的问题。我不知道这是缺乏知识,还是事实上在Javascript中根本不可能,但我希望能够了解它。
我正在尝试执行对象中的函数别名列表。执行这些函数时,我想像直接从实例本身执行它们一样使用它们,这样我就可以在被调用的方法中使用其他方法和实例变量。为了让我的解释更清楚,这里有一个例子:
class Bar {
constructor() {
this.name = "Bar";
}
someMethod() {
console.log(this.name) // should log Bar
}
}
class Foo {
constructor() {
this.name = "Foo";
}
someOtherMethod() {
console.log(this.name) // should log Foo
}
}
const bar = new Bar();
const foo = new Foo();
const methodList = {
foo: bar.someMethod,
baz: foo.someOtherMethod,
}
for(let prop in methodList) {
methodList[prop](); // logs 2x undefined
}
for(let prop in methodList) {
methodList[prop].apply(foo); //logs 2x Foo
}
从上面的例子中可以看出,this.name
是类实例中的一个变量。执行第二个循环时,将按预期应用上下文并正确记录。我希望看到自动应用上下文,因为函数别名对象是在不同的文件中执行的,不知道 foo
或 bar
并且只是接收列表。
有什么办法可以实现这一点吗?
最佳答案
您可以将 foo
和 bar
方法包装在它们自己的函数中。在这些方法中,您可以在对象上调用对象的方法 someMethod()
/someOtherMethod()
,如下所示:
const methodList = {
foo: (...args) => bar.someMethod(...args),
baz: (...args) => foo.someOtherMethod(...args),
}
目前,您的第一个循环不起作用,因为您的 this
并未引用对象的实际上下文,因为这不是用于调用该方法的内容。相反,它引用您的 methodList
参见下面的示例:
class Bar {
constructor() {
this.name = "Bar";
}
someMethod() {
console.log(this.name) // should log Bar
}
}
class Foo {
constructor() {
this.name = "Foo";
}
someOtherMethod() {
console.log(this.name) // should log Foo
}
}
const bar = new Bar();
const foo = new Foo();
const methodList = {
foo: (...args) => bar.someMethod(...args),
baz: (...args) => foo.someOtherMethod(...args),
}
for(let prop in methodList) {
methodList[prop](); // correct logs
}
关于javascript - 一般将上下文应用于方法别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56646489/