Reputation: 468
Say I want to pass around a reference to a method of a class in JavaScript:
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()
Weird example, but say I have more legitimate reasons for wanting these references without an instance of the object. Is there a clean way to do so?
Upvotes: 0
Views: 210
Reputation: 522016
The methods exist on the object's prototype. To call a detached method on an object instance, use .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);
Upvotes: 1