首页 > 解决方案 > 通常将上下文应用于方法别名

问题描述

我遇到了一个我无法解决的问题。不知道是知识匮乏,还是 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是类实例中的一个变量。执行第二个循环时,将应用上下文并按预期正确记录。我希望看到该上下文被自动应用,因为函数别名对象在不同的​​文件中执行,不知道foobar只是接收列表。

有什么办法可以做到这一点?

标签: javascriptecmascript-6

解决方案


您可以将您的foobar方法包装在它们自己的函数中。在这些方法中,您可以像这样在对象上调用对象的方法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
}


推荐阅读