this – Simulating an Object Method

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

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

object . function ( parameters .. )

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

The only way for a script-defined function to change an external value is via this.


#![allow(unused)]
fn main() {
fn change() {       // not that the object 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
}