KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
How do I emulate PHP-style __get() and __set() magic getter/setters in JavaScript? A lot of people say that this is currently impossible. I am almost certain that it is possible because projects like nowjs ( http://nowjs.com ) do something like this. I know that you can utilize get and set , but these don't work when you're not sure what the property name will be. For example, what if you wanted an event handler to execute when a new property is created ? Example of what I'd want to do: var obj = {}; notify(obj, function(key, value) { //key is now the name of the property being set. //value is the value of the property about to be set console.log("setting " + key + " to " + value); }); obj.foo = 2; //prints "setting foo to 2" obj.bar = {a: 2}; //prints "setting bar to [Object]" //Notice that notify() worked even though 'foo' and 'bar' weren't even defined yet! (The question is similar to the following questions: Is there a way to monitor changes to an object? JavaScript getter for all properties ) EDIT: It looks like this feature is called "dynamic proxies" and should appear in the ECMAScript "Harmony" standard (probably ES6). You can read more here . A new 'Proxy' Object is introduced with a couple methods (I.e. Create() and createFunction() ). One could do this: //Const
Tags (comma-separated)
Save Edits
Cancel