是否可以将导入的函数分配为类方法,以使其自动进入对象原型链?
// 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()
我可以使用constructor
在此this.testMethod = testMethod
中附加该方法,但该方法未在对象原型链上进行。
答案 0 :(得分:4)
分配.prototype
的{{1}}属性,以便TestClass
的实例将看到导入的方法:
TestClass
class TestClass {
}
TestClass.prototype.testMethod = testMethod;