JavaScript的獲取者爲Object.defineProperty
。因此,我可以通過在JavaScript中定義通用/退回獲取器屬性
Object.defineProperty(window, 'random', {
get: function() {
return Math.random();
}
});
random // Evaluates to a random number
定義上的window
財產random
一個getter是否有可能定義一個「萬能吸附劑」給定對象,無論對象屬性的?我期待做類似
Object.universalGetter(window, function (propertyName) {
console.log('Accessing property', propertyName, 'of window.');
});
window.Function // Prints "Accessing property Function of window."
我可以在JavaScript中使用「通用getters」嗎?
的[可能重複是否有可能在JavaScript中實現動態getter/setter?](http://stackoverflow.com/questions/7891937/is-it-possible-to-implement-dynamic-getters-setters-in-javascript) – user123444555621 2013-02-13 20:24:01
另請參閱http:// stackoverflow .com/questions/2266789/is-there-an-equivalent-of-the-nosuchmethod-feature-for-properties-or-a-way – user123444555621 2013-02-13 20:27:41