Reputation: 2405
Is it possible to assign an imported function as a class method, so that it automatically goes on an objects prototype chain?
// Module
module.exports = function testMethod() {
console.log('From test method')
}
// Main
const testMethod = require('./testMethod')
class TestClass {
// Replace this method with imported function
testMethod() {
console.log('From test method')
}
}
const obj = new TestClass()
I was able to attach the method in this constructor
using this.testMethod = testMethod
but the method did not go on an objects prototype chain.
Upvotes: 1
Views: 298
Reputation: 370679
Assign to the .prototype
property of the TestClass
so that instances of TestClass
will see the imported method:
class TestClass {
}
TestClass.prototype.testMethod = testMethod;
const testMethod = () => console.log('test method');
class TestClass {
}
TestClass.prototype.testMethod = testMethod;
const tc = new TestClass();
tc.testMethod();
Upvotes: 4