问题
Using Object.create one can define setter and getter methods in javascript.
o = Object.create(Object.prototype, {
fooBar: {
get: function() { return "Meh" },
set: function(value) { console.log(value) }
}
});
console.log(o)
will always return Meh, and doing o = "Heyo"
would only output the new value directly without changing o
.
Is there any reason as to why I should not use, or rely on this behavior to trigger events? What about two-way binding frameworks like angular and ember, do they make use of this feature? What about unit-testing?
What is the defacto standard way of watching for changes to trigger events, without using explicit setters and getters?
回答1:
There are three ways to observe changes in JavaScript objects:
- Methods (as for example your set/get, or combined)
- Polling using a timer to check a property
- Observers to handle properties which is handled internally by the browser
Method 1 is common and simple. If you want to use setter/getter is up to you. There is also the option of using them combined:
var someValue = 0;
this.myMethod = function(newValue) {
if (arguments.length === 0) return someValue; /// gets if no arg is given
someValue = newValue; /// sets if arg is given
return this;
}
It's clean and straight forward.
If you want to use properties instead you need to either use polling using a timer or you can use an object observer.
However the current support for Object observers is not that great (last time I checked). Chrome has support, Firefox has its own observer system and so forth so if you use those you need to prepare your code to handle situations where it isn't supported. This basically means you need to poll instead. Therefor method with set/get etc. is a better approach IMO.
An observer is useful with properties. It will allow you to set a property this way:
myObject.value = 10;
and trigger a callback that allows you to handle that change. Note it will trigger callback on any property change so need to iterate the events.
For example:
Object.observe(myObject, observerCallback);
function observerCallback(records) {
records.forEach(checkRecord);
}
function checkRecord(rec) {
switch(rec.name) {
case 'value':
handleValueChange();
break;
}
}
来源:https://stackoverflow.com/questions/20388229/is-using-javascript-setters-and-getter-properties-to-watch-for-changes-a-bad-ide