Last active
August 29, 2015 14:01
-
-
Save blindman2k/5f6d32c141970ea2e5a1 to your computer and use it in GitHub Desktop.
Overriding imp's built-in objects can be fun :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is a really simple, reusable wrapper for any internal object to turn it into a class. | |
// For memory and performance reasons, the built-in classes are not real classes so can't | |
// be extended in the normal way. | |
class impWrapper { | |
_wrapped = null; | |
constructor(wrapped) { | |
_wrapped = wrapped; | |
} | |
// Pass through the original methods and properties | |
function _get(idx) { | |
if (idx in this) { | |
return this[idx]; | |
} else if (idx in _wrapped && typeof _wrapped[idx] == "function") { | |
return _wrapped[idx].bindenv(_wrapped); | |
} else if (idx in _wrapped) { | |
return _wrapped[idx]; | |
} else { | |
throw null; | |
} | |
} | |
} | |
// This is a specific example that extends the "server" class by overriding | |
// the log() function and letting all the other functions work as normal. | |
class newServer extends impWrapper { | |
// Pass the "server" object into the base constructor | |
constructor() { | |
base.constructor(server); | |
} | |
// Override the log functions | |
function log(msg) { | |
if (typeof msg == "table" || typeof msg == "array") { | |
_wrapped.log(http.jsonencode(msg)); | |
} else { | |
_wrapped.log(msg); | |
} | |
} | |
} | |
server <- newServer(); | |
server.save({"This": "still works fine"}) | |
server.log(server.load()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment