Thursday, 25 May 2017

How can I implement ruby extend module in javascript like the example?

In ruby I can extend a module on a object in run time, I think javascript should can get the function, but I can get it try for a long time, anyone know how can get it? My example code in the below.

ruby => run 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 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()



via Tsao

No comments:

Post a Comment