【问题标题】:How to implement Ruby's extend module in JavaScript如何在 JavaScript 中实现 Ruby 的扩展模块
【发布时间】:2017-10-26 11:39:05
【问题描述】:

在 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 返回一个 TypeError: test_new.test2 is not a function

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 ruby-on-rails ruby node.js


【解决方案1】:

这似乎对我有用:

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

【讨论】:

  • 谢谢,可以,但是如果我的 Other 类有很多方法,我不想单独附加每个方法,我该怎么办?
  • 迭代其他方法
  • 我不想迭代,我使用的下面的代码似乎至少是最好的方法。
  • class Test { constructor(name) { //super(props); this.name = name; } test1(){ return this.name } } const Other = { test2: function(){ return this.name }, test3: function(){ return this.name } } console.log(Object.getOwnPropertyNames( Test.prototype )) console.log(Test.prototype) var test = new Test("HKE") var test_new = Object.assign(test,Other) console.log(test_new.test1()) console.log(test_new.test2()) console.log(test_new.test3())
  • wanna 什么时候变成了一个词?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-24
  • 2012-12-19
  • 2017-05-20
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
相关资源
最近更新 更多