使用JSContext在swift中调用匿名javascript函数

时间:2015-06-17 18:13:13

标签: javascript swift

我发现如何使用JSContext在swift中调用命名的javascript函数。像这样:

let context = JSContext()
context.evaluateScript("function sum(a,b) { return a+b; }")
let sumFunction = context.objectForKeyedSubscript("sum")
let result = sumFunction.callWithArguments([5,3])
println("Sum = \(result.toInt32())")

但是,我如何调用一个给我的匿名javascript函数

(a,b) { return a+b;}

注意“sum”函数名丢失,因此是匿名的,这是正确的javascript语法

2 个答案:

答案 0 :(得分:2)

怎么样

import JavaScriptCore
let context = JSContext()
let value : JSValue = context.evaluateScript("(function (a,b) { return a+b; })")
let result = value.invokeMethod("call", withArguments: ["this",1,2])
print(result.toInt32())

答案 1 :(得分:1)

根据Christian的反馈意见,我通过将其分配给这样的变量来找出问题的解决方案:

CREATE (TheMatrix:Movie {title:'The Matrix', released:1999, tagline:'Welcome to the Real World'})
CREATE (Keanu:Person {name:'Keanu Reeves', born:1964})
CREATE (Carrie:Person {name:'Carrie-Anne Moss', born:1967})
CREATE (Laurence:Person {name:'Laurence Fishburne', born:1961})
CREATE (Hugo:Person {name:'Hugo Weaving', born:1960})