【问题标题】:Call method on class by method reference通过方法引用在类上调用方法
【发布时间】:2019-07-17 04:26:24
【问题描述】:

我有一个名为func 的引用链接到一个名为method 的静态方法,当我调用func() 时,该方法找不到静态方法_open。我不知道为什么,但我认为这是因为func 是一种方法,我这样称呼它。

看起来像这样:

class A {
  static method() {
    this._open()
  }
  static _open() {
    // Do stuff
  }
}

我试过这样调用方法:

/**
 * Finds the data in a object/array if it exists
 * `a.b.c` -> `{a: {b: {c: 'some value'}}}`
 */
function find(query, data) {
  return query.split('.').reduce((obj, val) => {
    return obj ? obj[val] : obj
  }, data)
}

// func is a reference to `method`
let func = find('A.method', {A: A})
func.constructor.prototype[func](...params)

但是,它给了我这个错误:

TypeError: func.constructor.prototype[func] 不是函数

当记录 func 时,它看起来像这样:

console.log(func.toString())
// Output:
// method() {
//   this._open()
// }

如何在仅引用方法的类上调用静态方法?

【问题讨论】:

  • 你不应该一直使用A._open()而不是this._open()来调用静态方法_open吗?
  • 你不需要,因为它们都是静态的
  • A.method.constructorFunction 不是 A。如果没有对A 的引用,那么如果您只有对method 的引用,则没有任何东西可以将method 与它联系起来。它不“知道”这是一种方法。

标签: javascript


【解决方案1】:

你需要确保find返回的方法是绑定到A的,否则当method被调用时,this会引用全局的thiswindow或者undefined),然后你可以打电话给func():

class A {
  static method(...args) {
    console.log('args', args);
    this._open()
  }
  static _open() {
    console.log('opening');
  }
}

const find = () => A.method.bind(A);

const func = find('method');
func('abc', 'def');

如果您只有对func 的引用,而不是对 A 类的引用,则无法再次访问 A。仅当 funcinstance 时,引用 func.constructor 才有意义(在这种情况下,引用其 .constructor 会将您带到 A) - 但 func 是该类的方法,而不是类的实例。

如果你需要动态检测find返回值之前的最后一个对象是什么,所以你可以根据需要绑定函数,在find函数中添加更多逻辑,以获取最后一个对象最后一个键:

class A {
  static method() {
    this._open()
  }
  static _open() {
    console.log('opening');
  }
}

function find(query, data) {
  const keys = query.split('.');
  const lastKey = keys.pop();
  const lastObj = keys.reduce((obj, val) => {
    return obj ? obj[val] : obj
  }, data);
  const ret =  lastObj[lastKey];
  return typeof ret === 'function' ? ret.bind(lastObj) : ret;
}

// func is a reference to `method`
let func = find('A.method', {
  A: A
});
func('param 1', 'param 2')

【讨论】:

  • 如果有帮助的话,我已经添加了我的 find 函数的样子。所以我不认为我有直接的参考。
  • 太棒了!我现在已经在我自己的项目中使用它了!
【解决方案2】:

不太清楚,你这样做是为了什么:

class A {
  static method() {
    return this._open(...arguments)
  }
  static _open() {
    return arguments;
    // Do stuff
  }
}
function find(classHere, method){
  return classHere[method].bind(classHere);
}
var func = find(A, 'method');
console.log(func('test', 'is', 'this', 'what', 'you', 'want'));

【讨论】:

    猜你喜欢
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多