2013-02-13 14 views
8

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」嗎?

+0

的[可能重複是否有可能在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

+1

另請參閱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

回答

4

這是不可能的ECMAScript的第5版做,因爲沒有規定進行此操作。雖然沒有明確說明,但可以看出,[GetProperty]沒有對不存在的屬性作出任何規定。

的干將/ ECMAScript中制定者需要現有的屬性並沒有Ruby的method_missing或Python的__getattribute__的等價物。

10

不幸的是:沒有,沒有。

還有就是somehthing稱爲Proxy對象在壁虎18推出了基於瀏覽器

這將允許你做這樣的事情

(function (original, Window) { 
    var handler = { 
    get: function (target, propertyName) { 
     console.log('Accessing property', propertyName, 'of window.'); 
     return target[propertyName]; 
    } 
    }; 

    Window = new Proxy(original, handler); 


    console.log(Window.setTimeout); 
    // "Accessing property" 
    // "setTimeout" 
    // "of window." 

    // function setTimeout() { 
    // [native code] 
    // } 
})(window); 

但這標準,仍然很不穩定

順便說一句,我原本以爲你可以直接使用window作爲IIFE的局部變量,但似乎你不能它只是原木不確定的(不知道爲什麼),所以我大寫的「W」

這裏有一個例子在JSBin

注:您應該訪問在Firefox

+1

['Proxy'](https://developer.mozilla。 org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)現已成爲標準,並正在作爲ES2015的一部分實施 – CletusW 2016-08-31 19:11:19

相關問題