如果我有一个javascript对象,我通常会像这样与对象及其方法交互:
var obj = someObject.getInstance();
var result = obj.someMethod();其中someMethod的定义如下:
someObject.prototype.someOtherMethod = function() { //do stuff };
someObject.prototype.someMethod = function(foo) { this.someOtherMethod(); };然而,当我想通过ExecJS调用Ruby语言中的someMethod时,我得到了一个错误:
context = ExecJS.compile(# the javascript file)
context.call('someObject.getInstance().someMethod')
# Gives a TypeError where Object has no method 'someOtherMethod'另一方面,javascript模块中定义的函数运行良好:
someFunction = function() { // do stuff };
# in Ruby
context.call('someFunction') # does stuffExecJS可以处理Javascript对象和它们的方法吗,或者我只能用它调用函数?
关于具体的应用程序,我正在研究https://github.com/joenoon/libphonenumber-execjs,但由于上述原因,Libphonenumber中的解析函数不起作用。
发布于 2012-12-24 09:37:59
通过一些实验找到了答案。通过使用context.exec()而不是调用,我设法获得了所需的功能。
js = <<JS
var jsObj = someObject.getInstance();
var res = jsObj.someMethod();
return res;
JS
context.exec(js);但是,如果您的方法返回一个Javascript对象,您必须首先序列化它,或者解析结果,以便ExecJS可以将其返回到合适的Ruby对象中。
https://stackoverflow.com/questions/13967576
复制相似问题