所以我想了解一下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的正确行为还是我做错了什么?
提前谢谢你!
发布于 2015-01-01 18:48:49
我意识到我做错了什么。
因为它是一个类,所以在调用它的方法之前,我首先需要创建一个对象。
这就是怎么做的:
JSValue* c = [_context[@"testClass"] constructWithArguments:@[]];
[c invokeMethod:@"toto" withArguments:@[]];https://stackoverflow.com/questions/27725078
复制相似问题