JavaScriptKit Documentation Beta

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")
%3 JSFunction JSFunction JSObject JSObject JSFunction->JSObject JSClosure JSClosure JSClosure->JSFunction

Superclass

JSObject

JSObject represents an object in JavaScript and supports dynamic member lookup. Any member access like object.foo will dynamically request the JavaScript and Swift runtime bridge library for a member with the specified name in this object.

Subclasses

JSClosure

JSClosure represents 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 of JSClosure should 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

call​AsFunction(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

this JSObject?

The value to be passed as the this parameter to this function.

arguments [Convertible​ToJSValue]

Arguments to be passed to this function.

Returns

The result of this call.

call​AsFunction(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 this value, or

  • c. the constructor returns undefined, null or a non-object, in which case JS also returns this.

Parameters

arguments [Convertible​ToJSValue]

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?

js​Value()

override public func jsValue() -> JSValue