gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:18:09 25 4
gpt4 key购买 nike

在 Ruby 中,我可以在运行时扩展对象上的模块。我认为 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()

有谁知道我怎样才能得到它?

最佳答案

这似乎对我有用:

> 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

它返回othertest2 元素,即函数test2。还有这个:

> test["test2"] = other.test2

只需将该函数添加到test 的函数数组中。然后你可以调用:

> test.test2()

关于javascript - 如何在JavaScript中实现Ruby的扩展模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44186968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com