所以我试图了解JavascriptCore的工作原理。
所以首先我尝试调用单个函数,但现在我正在尝试调用类中的函数。
我的javascript代码看起来像这样
var sayHelloAlfred = function()
{
log("Hello Alfred");
}
var testClass = function()
{
this.toto = function()
{
log("Toto in class");
}
}
var testObject = {
toto : function()
{
log("Toto in object");
}
}
我的ViewController代码:
- (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
}
我的问题是,它与对象中的单个函数和函数完美配合,但在函数中却没有。
你知道这是JavaScriptCore的正确行为还是我做错了什么?
提前多多感谢!
答案 0 :(得分:1)
我意识到我做错了什么。
因为它是一个类,所以我首先需要在调用它的方法之前创建一个对象。
这是怎么做的:
JSValue* c = [_context[@"testClass"] constructWithArguments:@[]];
[c invokeMethod:@"toto" withArguments:@[]];