rhai/scripts/oop.rhai

42 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-08-04 12:39:24 +02:00
// This script simulates object-oriented programming (OOP) techniques using closures.
// External variable that will be captured.
let last_value = ();
2020-06-27 11:34:39 +02:00
// Define object
let obj1 = #{
2020-08-04 12:39:24 +02:00
_data: 42, // data field
get_data: || this._data, // property getter
2021-04-04 17:22:45 +02:00
action: || print(`Data=${this._data}`), // method
2020-08-04 12:39:24 +02:00
update: |x| { // property setter
this._data = x;
last_value = this._data; // capture 'last_value'
this.action();
}
2020-06-27 11:34:39 +02:00
};
2020-08-04 12:39:24 +02:00
if obj1.get_data() > 0 { // property access
obj1.update(123); // call method
2020-06-27 11:34:39 +02:00
} else {
print("we have a problem here");
}
// Define another object based on the first object
let obj2 = #{
2020-08-04 12:39:24 +02:00
_data: 0, // data field - new value
update: |x| { // property setter - another function
this._data = x * 2;
last_value = this._data; // capture 'last_value'
this.action();
}
2020-06-27 11:34:39 +02:00
};
2020-08-04 12:39:24 +02:00
obj2.fill_with(obj1); // add all other fields from obj1
2020-06-27 11:34:39 +02:00
2020-08-04 12:39:24 +02:00
if obj2.get_data() > 0 { // property access
print("we have another problem here");
2020-06-27 11:34:39 +02:00
} else {
2020-08-04 12:39:24 +02:00
obj2.update(42); // call method
2020-06-27 11:34:39 +02:00
}
2020-08-04 12:39:24 +02:00
2021-04-04 17:22:45 +02:00
print(`Should be 84: ${last_value}`);