1

So I'm trying to understand how JavascriptCore works.

So first I tried calling single function, but now I'm trying to call a function inside a class.

My javascript code looks like this

var sayHelloAlfred = function()
{
    log("Hello Alfred");
}

var testClass = function()
{
    this.toto = function()
    {
        log("Toto in class");
    }
}

var testObject = {

    toto : function()
    {
        log("Toto in object");
    }

}

And my ViewController code :

- (void)viewDidLoad {
    [super viewDidLoad];

    _context = [[JSContext alloc] initWithVirtualMachine:[[JSVirtualMachine alloc] init]];

    _context[@"log"] = ^(NSString *text) {
        NSLog(@"%@", text);
    };

    NSString *scriptFilePath = [[NSBundle mainBundle] pathForResource:@"main" ofType:@"js"];
    NSString *scriptFileContents = [NSString stringWithContentsOfFile:scriptFilePath encoding:NSUTF8StringEncoding error:nil];
    [_context evaluateScript:scriptFileContents];
}

- (IBAction)doStuff:(id)sender
{
    [_context[@"sayHelloAlfred"] callWithArguments:@[]]; // Works
    [_context[@"testClass"] invokeMethod:@"toto" withArguments:@[]]; // Doesn't work
    [_context[@"testObject"] invokeMethod:@"toto" withArguments:@[]]; // Works
}

My problem is that it works perfectly with a single function and a function in an object but not with this in a function.

Do you know if this is the correct behavior of JavaScriptCore or if I'm doing something wrong ?

Thanks a lot in advance!

1 Answer 1

1

I realized that I was doing something wrong.

Since it's a class I first need to create an object before calling its methods.

That's how to do it :

JSValue* c = [_context[@"testClass"] constructWithArguments:@[]];
[c invokeMethod:@"toto" withArguments:@[]];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.