【问题标题】:Javascript: Passing a method that is callable with a "this" objectJavascript:传递可使用“this”对象调用的方法
【发布时间】:2021-10-25 22:28:32
【问题描述】:
class Foo {
  constructor(bar) {
    this.bar = bar
  }

  getBar() {
    return this.bar
  }
}

function unmethodize(f) {
  return function(object, ...args) {
    return f.apply(object, args)
  }
}

const unmethodizedGetBar = unmethodize(Foo.prototype.getBar)

function test() {
  foos = [new Foo(1), new Foo(2), new Foo(3)]
  return foos.map(unmethodizedGetBar)
}

我知道foos.map(foo => foo.getBar())等。

我只想要一个getBar 的版本,它将“this”对象作为其第一个参数。它是否已经存在于某个地方,或者我必须通过unmethodize 或类似的方式创建它?

【问题讨论】:

  • 没有任何内置功能可以做到这一点。

标签: javascript


【解决方案1】:

它是否已经存在于某个地方?

不,您必须自己创建它。您的类中的 getBar 仅定义了一个需要 this 参数的方法。

如果您不想使用箭头函数或编写自己的 unmethodize 函数,则只能使用内置函数来实现:

但是认真地使用箭头函数:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 2011-11-11
    • 1970-01-01
    相关资源
    最近更新 更多