Class
JSFunction
public class JSFunction: JSObject
JSFunction represents a function in JavaScript and supports new object instantiation.
This type can be callable as a function using callAsFunction.
e.g.
let alert: JSFunction = JSObject.global.alert.function!
// Call `JSFunction` as a function
alert("Hello, world")
Relationships
Superclass
JSObjectJSObjectrepresents an object in JavaScript and supports dynamic member lookup. Any member access likeobject.foowill dynamically request the JavaScript and Swift runtime bridge library for a member with the specified name in this object.
Subclasses
JSClosureJSClosurerepresents a JavaScript function the body of which is written in Swift. This type can be passed as a callback handler to JavaScript functions. Note that the lifetime ofJSClosureshould be managed by users manually due to GC boundary between Swift and JavaScript. For further discussion, see also swiftwasm/JavaScriptKit #33
Properties
`throws`
var `throws`: JSThrowingFunction
A modifier to call this function as a throwing function
function validateAge(age) {
if (age < 0) {
throw new Error("Invalid age");
}
}
let validateAge = JSObject.global.validateAge.function!
try validateAge.throws(20)
Methods
callAsFunction(this:arguments:)
@discardableResult public func callAsFunction(this: JSObject? = nil, arguments: [ConvertibleToJSValue]) -> JSValue
Call this function with given arguments and binding given this as context.
Parameters
| Name | Type | Description |
|---|---|---|
| this | JSObject? |
The value to be passed as the |
| arguments | [ConvertibleToJSValue] |
Arguments to be passed to this function. |
Returns
The result of this call.
callAsFunction(this:_:)
@discardableResult public func callAsFunction(this: JSObject? = nil, _ arguments: ConvertibleToJSValue) -> JSValue
A variadic arguments version of callAsFunction.
new(arguments:)
public func new(arguments: [ConvertibleToJSValue]) -> JSObject
Instantiate an object from this function as a constructor.
Guaranteed to return an object because either:
-
a. the constructor explicitly returns an object, or
-
b. the constructor returns nothing, which causes JS to return the
thisvalue, or -
c. the constructor returns undefined, null or a non-object, in which case JS also returns
this.
Parameters
| Name | Type | Description |
|---|---|---|
| arguments | [ConvertibleToJSValue] |
Arguments to be passed to this constructor function. |
Returns
A new instance of this constructor.
new(_:)
public func new(_ arguments: ConvertibleToJSValue) -> JSObject
A variadic arguments version of new.
from(_:)
@available(*, unavailable, message: "Please use JSClosure instead") public static func from(_: @escaping ([JSValue]) -> JSValue) -> JSFunction
construct(from:)
public override class func construct(from value: JSValue) -> Self?
jsValue()
override public func jsValue() -> JSValue