将导入的函数分配为类方法?

时间:2019-08-26 23:41:23

标签: javascript

是否可以将导入的函数分配为类方法,以使其自动进入对象原型链?

// 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中附加该方法,但该方法未在对象原型链上进行。

1 个答案:

答案 0 :(得分:4)

分配.prototype的{​​{1}}属性,以便TestClass的实例将看到导入的方法:

TestClass

class TestClass {
}
TestClass.prototype.testMethod = testMethod;