如何在 JavaScript 中实现 Ruby 的扩展模块 [英] How to implement Ruby's extend module in JavaScript

查看:41
本文介绍了如何在 JavaScript 中实现 Ruby 的扩展模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,我可以在运行时在对象上扩展模块.我认为 JavaScript 可以获得该功能,但我无法使其工作.

In Ruby I can extend a module on a object at run time. I think JavaScript can get the function, but I can't get it to work.

Ruby 运行正常,对象有 test1test2 方法:

Ruby runs OK, the object has test1 and test2 methods:

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 不是函数

JavaScript returns a 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()

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

Does anyone know how I can get it?

推荐答案

这似乎对我有用:

> 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

一个实例实际上只是一个函数数组(在这种情况下).所以,当你打电话时:

An instance is really just an array of functions (in this case). So, when you call:

other.test2

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

It returns the test2 element of other which is the function test2. And this:

> test["test2"] = other.test2

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

just add that function to the array of functions for test. Which you can then call with:

> test.test2()

这篇关于如何在 JavaScript 中实现 Ruby 的扩展模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆