【发布时间】: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.constructor是Function不是A。如果没有对A的引用,那么如果您只有对method的引用,则没有任何东西可以将method与它联系起来。它不“知道”这是一种方法。
标签: javascript