Created
July 12, 2011 22:24
-
-
Save rickosborne/1079133 to your computer and use it in GitHub Desktop.
Enforced getters and setters in JavaScript?
This file contains 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 o = (function(){ | |
var properties = { | |
color : { value: "red" }, | |
size : { value: "large", set: false }, | |
secret : { value: "cookies", get: false } | |
}; | |
return { | |
// this only exists in Mozilla? | |
__noSuchMethod__: function (name, args) { | |
// the name argument is the called method | |
var action = name.substr(0,3); | |
// we only handle getters and setters | |
if ((action !== "get") && (action !== "set")) { return; } | |
// there must be a property name | |
if (name.length < 4) { return; } | |
// allow camel case by lowercasing all property names | |
var key = name.substr(3).toLowerCase(); | |
// only use existing properties | |
if (!(key in properties)) { return; } | |
if (action === "set") { | |
// did we get any arguments? | |
if (args.length < 1) { return; } | |
if (("set" in properties[key]) && (properties[key].set === false)) { | |
console.warn("Attempt to write to a read-only property: " + key); | |
} else { | |
properties[key].value = args[0]; | |
} | |
// allow chaining | |
return this; | |
} else { | |
// must be a getter | |
if (("get" in properties[key]) && (properties[key].get === false)) { | |
console.warn("Attempt to read from a write-only property: " + key); | |
return; | |
} | |
return properties[key].value; | |
} | |
} | |
}; | |
})(); | |
console.log(o.getColor()); // should say "red" | |
console.log(o.setColor("blue").getColor()); // should say "blue" | |
console.log(o.getColor()); // should say "blue" | |
// these are not allowed so we should get a warning | |
console.log(o.setSize("big").getSize()); | |
o.setSecret("cupcake").getSecret(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment