Instance Method


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


func setObject(_ object: Any!, forKeyedSubscript key: (NSCopying & NSObjectProtocol)!)



The value to set for the JavaScript property.


The JavaScript property name to use in the context’s global JavaScript object.


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];

See Also

Accessing JavaScript Global State with Subscripts

func objectForKeyedSubscript(Any!) -> JSValue!

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