<!--
{
  "availability" : [
    "iOS: 16.0.0 -",
    "iPadOS: 16.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.5.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "JavaScriptCore",
  "identifier" : "/documentation/JavaScriptCore/JSContext/setObject(_:forKeyedSubscript:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "JavaScriptCore"
    ],
    "preciseIdentifier" : "c:objc(cs)JSContext(im)setObject:forKeyedSubscript:"
  },
  "title" : "setObject(_:forKeyedSubscript:)"
}
-->

# setObject(_:forKeyedSubscript:)

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

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

## 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`](/documentation/JavaScriptCore/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:

```objc
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];
};
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)