2017-05-25 58 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