Reputation: 169
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!
Upvotes: 1
Views: 484
Reputation: 169
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:@[]];
Upvotes: 1