如何在JavaScript中实现Ruby的扩展模块

在Ruby中,我可以在运行时在对象上扩展一个模块。 我认为JavaScript可以得到的function,但我不能得到它的工作。

Ruby运行正常,对象有test1test2方法:

 class Test def test1 puts "test1" end end module Other def test2 puts "test2" end end test = Test.new test.extend(Other) test.test1 test.test2 

JavaScript返回一个TypeError:test_new.test2不是一个函数

 class Test { test1(){ console.log("test1") } } class Other { test2() { console.log("test2") } } console.log(Object.getOwnPropertyNames( Test.prototype )) console.log(Object.getOwnPropertyNames( Other.prototype )) var test = new Test var test_new = Object.assign(test, Other.prototype) test_new.test1() test_new.test2() 

有谁知道我怎么能得到它?

这似乎为我工作:

 > class Test { test1(){ console.log("test1") }} > class Other { test2() { console.log("test2") }} > test = new Test Test {} > other = new Other Other {} > test.test1() test1 > test["test2"] = other.test2 > test.test2() test2 

一个实例实际上只是一个函数数组(在这种情况下)。 所以,当你打电话给:

 other.test2 

它返回other函数test2test2元素。 和这个:

 > test["test2"] = other.test2 

只需将该函数添加到要test的函数数组即可。 然后你可以打电话给:

 > test.test2()