如何获得对 JavaScript 中的 class 方法的静态引用?
How do you get a static reference to a method of a class in JavaScript?
假设我想传递对 JavaScript 中 class 方法的引用:
class Example {
constructor() {
this.field = "value"
}
exampleMethod() {
console.log(this.field)
}
exampleMethod2() {
this.field += "."
}
}
// get references to the methods without having an instance of the object (important detail)
let methods = [Example.exampleMethod, Example.exampleMethod2] // not correct
let sampledMethod = methods[Math.floor(Math.random()*methods.length)]
let object = new Example()
object.sampledMethod()
奇怪的例子,但是说我有更合理的理由想要这些没有对象实例的引用。有干净的方法吗?
方法存在于对象的原型上。要在对象实例上调用分离方法,请使用 .call
or .apply
:
class Example {
constructor() {
this.field = "value"
}
exampleMethod() {
console.log(this.field)
}
exampleMethod2() {
this.field += "."
}
}
let methods = [Example.prototype.exampleMethod, Example.prototype.exampleMethod2];
let sampledMethod = methods[Math.floor(Math.random() * methods.length)];
let object = new Example();
console.log(object);
console.log('Calling', sampledMethod);
sampledMethod.call(object);
console.log(object);
假设我想传递对 JavaScript 中 class 方法的引用:
class Example {
constructor() {
this.field = "value"
}
exampleMethod() {
console.log(this.field)
}
exampleMethod2() {
this.field += "."
}
}
// get references to the methods without having an instance of the object (important detail)
let methods = [Example.exampleMethod, Example.exampleMethod2] // not correct
let sampledMethod = methods[Math.floor(Math.random()*methods.length)]
let object = new Example()
object.sampledMethod()
奇怪的例子,但是说我有更合理的理由想要这些没有对象实例的引用。有干净的方法吗?
方法存在于对象的原型上。要在对象实例上调用分离方法,请使用 .call
or .apply
:
class Example {
constructor() {
this.field = "value"
}
exampleMethod() {
console.log(this.field)
}
exampleMethod2() {
this.field += "."
}
}
let methods = [Example.prototype.exampleMethod, Example.prototype.exampleMethod2];
let sampledMethod = methods[Math.floor(Math.random() * methods.length)];
let object = new Example();
console.log(object);
console.log('Calling', sampledMethod);
sampledMethod.call(object);
console.log(object);