this – Simulating an Object Method


The only way for a script-defined [function](functions.md) to change an external value is via `this`.

Arguments passed to script-defined functions are always by value because functions are pure.

However, functions can also be called in method-call style:

object . method ( parameters)

When a function is called this way, the keyword this binds to the object in the method call and can be changed.

fn change() {       // note that the method does not need a parameter
    this = 42;      // 'this' binds to the object in method-call
}

let x = 500;

x.change();         // call 'change' in method-call style, 'this' binds to 'x'

x == 42;            // 'x' is changed!

change();           // <- error: 'this' is unbound

Elvis Operator

The Elvis operator can be used to short-circuit the method call when the object itself is [()].

object ?. method ( parameters)

In the above, the method is never called if object is [()].