在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