Skip to content

Latest commit

 

History

History
56 lines (41 loc) · 1.48 KB

decorator_this.mdx

File metadata and controls

56 lines (41 loc) · 1.48 KB
id keywords name summary category
this-decorator
this
decorator
@this
This is the `@this` decorator.
decorators

The @this decorator may be used to bind to an external callback function that require access to a this context.

Example

<CodeTab labels={["ReScript", "JS Output"]}>

type counter

// Function to create an empty object
@new external create: unit => counter = "Object"

// Functions that set and get a "value" property
@set external setValue: (counter, int) => unit = "value"
@get external getValue: counter => int = "value"

// Functions that create "increment" and "decrement" function properties which have access to "this"
@set external setIncrement: (counter, @this (counter, int) => unit) => unit = "increment"
@set external setDecrement: (counter, @this (counter, int) => unit) => unit = "decrement"

// Use the functions above to create a counter instance
let counter = create()
setValue(counter, 0)
setIncrement(counter, @this (me, amount) => me->setValue(me->getValue + amount))
setDecrement(counter, @this (me, amount) => me->setValue(me->getValue - amount))
var counter = new Object()

counter.value = 0

counter.increment = function (amount) {
  var me = this
  me.value = (me.value + amount) | 0
}

counter.decrement = function (amount) {
  var me = this
  me.value = (me.value - amount) | 0
}

References