2017-05-25 88 views
1

在Ruby中,我可以在運行時在對象上擴展模塊。我認爲JavaScript可以獲得這個功能,但我無法實現它的功能。如何在JavaScript中實現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返回一個類型錯誤: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() 

有誰知道我怎樣才能得到它?

+3

可能重複的[在JavaScript中克隆非枚舉屬性](https://stackoverflow.com/q/38316864/218196)。 –

+0

@FelixKling,是的,我發現它似乎是原因「原型鏈上的屬性和非枚舉屬性不能被複制」,謝謝。 – Tsao

+1

可能重複的[在JavaScript中克隆非枚舉屬性](https://stackoverflow.com/questions/38316864/cloning-non-enumerable-properties-in-javascript) – Tsao

回答

2

這似乎爲我工作:

> 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() 
+0

謝謝,這是工作,但如果我的其他類有很多方法,我不想單獨附上每種方法,我該怎麼辦? – Tsao

+0

重複其他方法 – jvillian

+0

我不想重複,下面我使用的代碼似乎至少是最好的方式。 – Tsao