Last active
August 29, 2015 14:04
-
-
Save Swivelgames/ca277d2bbf0c23cbef42 to your computer and use it in GitHub Desktop.
Messing around with things and trying to find a good way to make a string reference-able...
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
| var StringReference = function(scope, str) { | |
| if(str===void 0) { str = scope; scope = window; }; | |
| Object.defineProperty(scope, "__"+str, { | |
| configurable: true, | |
| enumerable: false, | |
| get: function(){ | |
| return scope[str]; | |
| }, | |
| set: function(val){ | |
| return scope[str] = val; | |
| } | |
| }); | |
| var ret = new Function(); | |
| ret.prototype.valueOf = ret.prototype.toString = function(){ | |
| return this.get(); | |
| }; | |
| ret.prototype.set = function(val) { | |
| return scope["__"+str] = val; | |
| }; | |
| ret.prototype.get = function() { | |
| return scope["__"+str] | |
| }; | |
| return new ret(); | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The nice thing about the "old fashioned," manually written getter/setter objects was that they were portable regardless of their value.
Using
myVar.getValue()andmyVar.setValue()would always update the variable in the initial scope back when we declared themyVarobject, and we could lug it around wherever we needed to. Unfortunately, we cannot do this with native setters/getters...