Hsiu Chuan Tsao
Hsiu Chuan Tsao

Reputation: 1566

How to implement Ruby's extend module in 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 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 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?

Upvotes: 1

Views: 411

Answers (1)

jvillian
jvillian

Reputation: 20263

This seems to work for me:

> 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

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

> test["test2"] = other.test2

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

> test.test2()

Upvotes: 2

Related Questions