forked from swiftwasm/JavaScriptKit
/
JSObject.swift
72 lines (57 loc) · 2.03 KB
/
JSObject.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import _CJavaScriptKit
@dynamicMemberLookup
public class JSObjectRef: Equatable {
internal var id: UInt32
init(id: UInt32) {
self.id = id
}
@_disfavoredOverload
public subscript(_ name: String) -> ((JSValueEncodable...) -> JSValue)? {
guard let function = self[name].function else { return nil }
return { (arguments: JSValueEncodable...) in
function(this: self, args: arguments)
}
}
public subscript(_ name: String) -> JSValue {
get { getJSValue(this: self, name: name) }
set { setJSValue(this: self, name: name, value: newValue) }
}
public subscript(_ index: Int) -> JSValue {
get { getJSValue(this: self, index: Int32(index)) }
set { setJSValue(this: self, index: Int32(index), value: newValue) }
}
@_disfavoredOverload
public subscript(dynamicMember name: String) -> ((JSValueEncodable...) -> JSValue)? {
guard let function = self[name].function else { return nil }
return { (arguments: JSValueEncodable...) in
function(this: self, args: arguments)
}
}
public subscript(dynamicMember name: String) -> JSValue {
get { self[name] }
set { self[name] = newValue }
}
public static func instanceof(_ instance: JSObjectRef, constructor: JSFunctionRef) -> Bool {
_instanceof(instance.id, constructor.id)
}
static let _JS_Predef_Value_Global: UInt32 = 0
public static let global = JSObjectRef(id: _JS_Predef_Value_Global)
deinit { _destroy_ref(id) }
public static func == (lhs: JSObjectRef, rhs: JSObjectRef) -> Bool {
return lhs.id == rhs.id
}
public convenience required init(jsValue: JSValue) {
switch jsValue {
case .object(let value):
self.init(id: value.id)
default:
fatalError()
}
}
public subscript(jsValue _: ()) -> JSValue {
.object(self)
}
public class func canDecode(from jsValue: JSValue) -> Bool {
return jsValue.isObject
}
}