Update docs and tests.

This commit is contained in:
Stephen Chung
2020-08-04 18:39:24 +08:00
parent b0ab6e95f5
commit 9f302d4ef5
8 changed files with 51 additions and 47 deletions

View File

@@ -1,45 +1,41 @@
// This script simulates object-oriented programming (OOP) techniques
// using function pointers (Fn) and object maps.
// This script simulates object-oriented programming (OOP) techniques using closures.
// External variable that will be captured.
let last_value = ();
// Define object
let obj1 = #{
_data: 42, // data field
get_data: Fn("getData"), // property getter
action: Fn("action"), // method
update: Fn("update1") // property setter
_data: 42, // data field
get_data: || this._data, // property getter
action: || print("Data=" + this._data), // method
update: |x| { // property setter
this._data = x;
last_value = this._data; // capture 'last_value'
this.action();
}
};
fn getData() {
this._data
}
fn action() {
print("Data=" + this._data);
}
fn update1(x) {
this._data = x;
this.action();
}
if obj1.get_data() > 0 { // property access
obj1.update(123); // call method
if obj1.get_data() > 0 { // property access
obj1.update(123); // call method
} else {
print("we have a problem here");
}
// Define another object based on the first object
let obj2 = #{
_data: 0, // data field - new value
update: Fn("update2") // property setter - another function
_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();
}
};
obj2.fill_with(obj1); // add all other fields from obj1
obj2.fill_with(obj1); // add all other fields from obj1
fn update2(x) {
this._data = x * 2;
this.action();
}
if obj2.get_data() > 0 { // property access
obj2.update(0); // call method
if obj2.get_data() > 0 { // property access
print("we have another problem here");
} else {
obj2.update(42); // call method
obj2.update(42); // call method
}
print("Should be 84: " + last_value);