JSContext (Objective-C)官方文档翻译

JSContext

继承自:NSObject
遵守协议:NSObject
导入声明:@import JavaScriptCore;
适用范围:iOS 7.0 及以后

一个 JSContext 对象代表一个 JavaScript 执行环境( execution environment)。你可以通过 Objective-C 或者 Swift 代码来创建和使用 JavaScript 上下文(contexts),这样你就可以去调用 JavaScript 的 scripts,获取 JavaScript 中定义的或计算的值,以及让原生的对象、方法、函数跟 JavaScript 交互。

一、创建 JavaScript 上下文(Creating JavaScript Contexts)

- init

Initializes a new JavaScript context.

Declaration

- (instancetype)init

Return Value
A new JavaScript context.

Discussion
This initializer creates a context along with a new, independent virtual machine (a JSVirtualMachine object). You cannot pass JavaScript values (JSValue objects) between contexts in different virtual machines. To create contexts that share a virtual machine, use the initWithVirtualMachine: initializer.

Availability
Available in iOS 7.0 and later.


- initWithVirtualMachine:

Creates a new JavaScript context associated with a specific virtual machine.

Declaration

- (instancetype)initWithVirtualMachine:(JSVirtualMachine *)virtualMachine

Parameters

参数 含义
virtualMachine The virtual machine with which to associate the new context.

Return Value
A new JavaScript context.

Discussion
By default, each context has an independent virtual machine (a JSVirtualMachine object). You cannot pass JavaScript values between contexts in different virtual machines. Use this initializer to create a context that shares its virtual machine with other JavaScript contexts to allow passing JSValue objects between those contexts.

Availability
Available in iOS 7.0 and later.

二、运行 JavaScript 脚本(Evaluating Scripts)

- evaluateScript:

Executes the specified JavaScript code.

Declaration

- (JSValue *)evaluateScript:(NSString *)script

Parameters

参数 含义
script The JavaScript source code to evaluate.

Return Value
The last value generated by the script. Note that a script can result in the JavaScript value undefined.

Discussion
Evaluating a script runs any top-level code and adds function and object definitions to the context’s global object.

Availability
Available in iOS 7.0 and later.


- evaluateScript:withSourceURL:

Executes the specified JavaScript code, treating the specified URL as its source location.

Declaration

- (JSValue *)evaluateScript:(NSString *)script
              withSourceURL:(NSURL *)sourceURL

Parameters

参数 含义
script The JavaScript source code to evaluate.
sourceURL A URL to be considered as the script’s origin.

Return Value
The last value generated by the script. Note that a script can result in the JavaScript value undefined.

Discussion
Evaluating a script runs any top-level code and adds function or object definitions to the context’s global object.
The sourceURL parameter is informative only; debuggers may use this URL when reporting exceptions.

Availability
Available in iOS 8.0 and later.

三、监听 JavaScript 运行时的回调状态(Evaluating Scripts)

+ currentContext

Returns the context currently executing JavaScript code.

Declaration

+ (JSContext *)currentContext

Return Value
The currently executing context, or nil if not within native code called from JavaScript.

Discussion
Call this method within an Objective-C or Swift block or method invoked from within JavaScript to obtain the JSContext object responsible for executing that Javascript code.
If not currently in code invoked as a callback from JavaScript, this method returns nil.

Availability
Available in iOS 7.0 and later.


+ currentCallee

Returns the currently executing JavaScript function.

Declaration

+ (JSValue *)currentCallee

Return Value
The currently executing JavaScript function, or nil if not within native code called from JavaScript.

Discussion
Call this method within an Objective-C or Swift block or method invoked from within JavaScript to obtain a JSValue object representing the JavaScript function responsible for executing that code.
If not currently in code invoked as a callback from JavaScript, this method returns nil.

Availability
Available in iOS 8.0 and later.


+ currentThis

Returns the value of the this keyword in currently executing JavaScript code.

Declaration

+ (JSValue *)currentThis

Return Value
The current value of the JavaScript this keyword, or nil if not within native code called from JavaScript.

Discussion
Call this method within an Objective-C or Swift block or method invoked from within JavaScript to obtain a JSValue object representing the current value of the this keyword in that JavaScript code.
If not currently in code invoked as a callback from JavaScript, this method returns nil.

Availability
Available in iOS 7.0 and later.


+ currentArguments

Returns the arguments to the current native callback from JavaScript code.

Declaration

+ (NSArray *)currentArguments

Return Value
The current callback arguments, or nil if not within native code called from JavaScript.

Discussion
Call this method within an Objective-C or Swift block or method invoked from within JavaScript to obtain an array of JSValue objects representing the arguments to the JavaScript function responsible for that callback.
If not currently in code invoked as a callback from JavaScript, this method returns nil.

Availability
Available in iOS 7.0 and later.

四、设置 JavaScript 全局状态(Working with JavaScript Global State)

globalObject Property

The JavaScript global object associated with the context. (read-only)

Declaration

@property(readonly, strong) JSValue *globalObject

Discussion
In a web browser, the global object of a JavaScript context is the browser window (the window object in JavaScript). Outside of web-browser use, a context’s global object serves a similar role, separating the JavaScript namespaces of different contexts. Global variables within a script appear as fields or subscripts in the global object—you can access them either through this JSValue object or through the methods listed in Accessing JavaScript Global State with Subscripts.

NOTE
For JSContext instances originating in WebKit, this method returns a reference to the WindowProxy object.

Availability
Available in iOS 7.0 and later.


exception Property

A JavaScript exception to be thrown in evaluation of the script.

Declaration

@property(strong) JSValue *exception

Discussion
Before performing a callback from JavaScript to an Objective-C or Swift block or method, the context preserves the prior value of this property and then sets its value to nil. After the callback has completed, the context reads the new value of the exception property—if this value is not nil, the context treats the value as an exception to be thrown in JavaScript as a result of the callback. After reading the property (and possibly throwing a JavaScript exception), the context restores the prior value of this property.
By default, JavaScriptCore assigns any uncaught exception to this property, so you can check this property’s value to find uncaught exceptions arising from JavaScript function calls. To change the exception handling behavior, use the exceptionHandler
property.

Availability
Available in iOS 7.0 and later.


exceptionHandler Property

A block to be invoked should evaluating a script result in a JavaScript exception being thrown.

Declaration

@property(copy) void (^exceptionHandler)( JSContext *context, JSValue *exception)

Discussion
The block takes the following parameters:

参数 含义
context The context in which the exception originates.
exception The JavaScript exception thrown.

The default value exception handler block stores its exception parameter value into the context’s exception property. As a consequence, the default behavior is that unhandled exceptions occurring within a callback from JavaScript to native code are thrown again upon return. Setting this value to nil results in all uncaught exceptions being silently consumed.

Availability
Available in iOS 7.0 and later.


virtualMachine Property

The JavaScript virtual machine to which the context belongs. (read-only)

Declaration

@property(readonly, strong) JSVirtualMachine *virtualMachine

Discussion
To create a context associated with a specific virtual machine, allowing JavaScript values to be passed between contexts that share the same virtual machine, use the initWithVirtualMachine: initializer.

Availability
Available in iOS 7.0 and later.


name Property

A descriptive name for the context.

Declaration

@property(copy) NSString *name

Discussion
This name appears when using remote debugging to examine the context.

Availability
Available in iOS 8.0 and later.

五、通过下标来获取 JavaScript 全局状态(Accessing JavaScript Global State with Subscripts)

- objectForKeyedSubscript:

Returns the value of the specified JavaScript property in the context’s global object, allowing subscript getter syntax.

Declaration

- (JSValue *)objectForKeyedSubscript:(id)*key*

Parameters

参数 含义
key The name of a JavaScript property in the context’s global JavaScript object.

Return Value
The JavaScript property named by key, or nil if no such field or function exists.

Discussion
This method first constructs a JSValue object from the key parameter, then uses that value in JavaScript to look up the name of a property in the context’s global object.

Availability
Available in iOS 7.0 and later.


- setObject:forKeyedSubscript:

Sets the specified JavaScript property of the context’s global object, allowing subscript setter syntax.

Declaration

- (void)setObject:(id)object
forKeyedSubscript:(NSObject <NSCopying> *)key

Parameters

参数 含义
object The value to set for the JavaScript property.
key The JavaScript property name to use in the context’s global JavaScript object.

Discussion
This method first constructs a JSValue object from the key
parameter, then uses that value in JavaScript to set the property in the context’s global object.
Use this method (or Objective-C subscript syntax) to bridge native objects or functions for use in JavaScript. For example, the following code creates a JavaScript function whose implementation is an Objective-C block:

JSContext *context = [[JSContext alloc] init];

context[@"makeNSColor"] = ^(NSDictionary *rgb){

float r = rgb[@"red"].floatValue;

float g = rgb[@"green"].floatValue;

float b = rgb[@"blue"].floatValue;

return [NSColor colorWithRed:(r / 255.f) green:(g / 255.f) blue:(b / 255.f) alpha:1.0];

};

Availability
Available in iOS 7.0 and later.

六、C JavaScriptCore 相关 API(Working with the C JavaScriptCore API)

JSGlobalContextRefProperty

Returns the C representation of the JavaScript context. (read-only)

Declaration

@property(readonly) JSGlobalContextRef JSGlobalContextRef

Discussion
See JSContextRef.h Reference for the C JavaScriptCore API.

Availability
Available in iOS 7.0 and later.


+ contextWithJSGlobalContextRef:

Creates a JavaScript context object from the equivalent C representation.

Declaration

+ (JSContext *)contextWithJSGlobalContextRef:(JSGlobalContextRef)jsGlobalContextRef

Parameters

参数 含义
jsGlobalContextRef A C JavaScript context reference.

Return Value
A JavaScript context object representing the same context.

Discussion
See JSContextRef.h Reference for the C JavaScriptCore API.

Availability
Available in iOS 7.0 and later.

参考(Reference)
https://developer.apple.com/library/ios/documentation/JavaScriptCore/Reference/JSContext_Ref/


问题:

  1. JSContext 对象的作用是什么?
  2. “JavaScript context” 是什么?
    3.virtual machine 在 JavaScript 中指的是什么?virtual machine 与 context 的关系?
    4.context’s global object 在 JavaScript 中指的是什么?
    5.window 在 JavaScript 中指的是什么?
  3. JavaScript Global State 是什么?
    7.如何将 Objective-C 中的 block 转成 JavaScript 中的函数?
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容

  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 8,840评论 0 6
  • 今天看《爱自己,和谁结婚都幸福》这本书,对这段话很有感触:通过你们的弱点,去发现你们的优势;通过你们的痛苦,去发现...
    885d352dfbfc阅读 162评论 0 0
  • 文/老显 五月底,六月初,阳光火辣,光阴飞梭无情,又是一年高考时。 高考前,莘莘学子在为了高考成功而低调地学习着,...
    老显阅读 1,256评论 15 10
  • —学员故事分享— 我接触股票是因为我妈,我上中学那阵子,住在姥姥家,我妈在家没什么事情,就开始跟着朋友学炒股,每天...
    壹园阅读 178评论 0 0
  • 酒后勿忘吸支烟,云雾缭绕玉皇前。 倘若吸烟你忘却,怎能驾云天庭玩。
    老槐树阅读 158评论 0 2