Search code examples
javascriptswiftjavascriptcore

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


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


Solution

  • It is simple, use invokeMethod method on returned value:

    let result = rectangle.invokeMethod("getArea", withArguments: [])
    

    You also need to fix your javascript for this to work:

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