在Ruby中,我可以在运行时在对象上扩展模块。我认为JavaScript可以获得这个功能,但我无法实现它的功能。如何在JavaScript中实现Ruby的扩展模块
红宝石运行正常,对象具有test1
和test2
方法:
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返回一个类型错误: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()
有谁知道我怎样才能得到它?
可能重复的[在JavaScript中克隆非枚举属性](https://stackoverflow.com/q/38316864/218196)。 –
@FelixKling,是的,我发现它似乎是原因“原型链上的属性和非枚举属性不能被复制”,谢谢。 – Tsao
可能重复的[在JavaScript中克隆非枚举属性](https://stackoverflow.com/questions/38316864/cloning-non-enumerable-properties-in-javascript) – Tsao