In Swift, how to invoke method of Jscript object returned by JSContext.callWithArguments

时间:2015-05-04 19:55:11

标签: javascript swift javascriptcore

I am new to both javascript and Swift. I am writing an IOS app, that uses JavaScriptCore to invoke a javascript function that returns an Object. How can I then use JavaScriptCore to invoke a method of the returned object.

for example (I'm not actually working with rectangles), the JavaScript might be as follows:

function Rectangle(l,w) {
    this.l = l
    this.w = w

    function area() {
        return l * w
    };
}

function getRectangle(l,w) {
    return new Rectangle(l,w)
}

And then, followng a call to jsContext.evaluateScript(jsScriptSource), the Swift calls to get a rectangle object might look like this

var getRectangle = self.jsContext.objectForKeyedSubscript("getRectangle")
var rectangle: JSValue = getRectangle.callWithArguments([11,5])

how can I then invoke the getArea method of the returned rectangle?

thanks

1 个答案:

答案 0 :(得分:2)

很简单,在返回值上使用let result = rectangle.invokeMethod("getArea", withArguments: []) 方法:

function Rectangle(l,w) {
  this.l = l
  this.w = w

  this.getArea = function area() {
    return l * w
  };
}

你还需要修复你的javascript才能工作:

xarr = np.array(xList)

N = xarr.size
range1 = np.arange(N)

mask = range1[:,None] < range1
out = ((mask*xarr)*xarr[:,None]).sum()