简体   繁体   中英

Javascript getters/setters on window

Why does the following throw a TypeError in firefox 21.0?

Object.defineProperty(window,'windowProperty',{
    get: function(){
        return 'windowProperty'
    },

    set: function(val){
        console.log('windowProperty is being set');
    },

    configurable: true,
});

var windowProperty;

But declaring windowProperty without using var works:

windowProperty;

Or

window.windowProperty;

This behavior is also present in spidermonkey:

var a=1;

Object.defineProperty(this,'a',{
    get: function(){
        return 'a';
    },
});

Writing only

windowProperty;

does not declare a variable. It just tries to return the variable content in the closest context or undefined if it can't be found. It's just like an assignment without a target. For example, you can also write random text without throwing an error:

'Hello, world !';
123456;
undefined;

Using var instead try to redefine a property which is already defined before in your code, so you have an error.

EDIT
As precised by simonzack, the browser does not always send an error when redefining a variable. For example:

var test; var test;

doesn't throw this error (even if it is a bad idea and some JS validators will warn you). By defining getters and setters, however, the browser 'locks' this property (to prevent collision, for example, two different setters on the same property). My bad, it's a misinterpretation.

Is there any reason why you want to redefine your variable?

EDIT 2
Taking into account that the var declaration went before the defineProperty , it allows to adds precision to my explanations. Indeed, when you first use the var declaration, the browser set its configurable state to false, which prevent doing changes on its descriptor ( See link ). So when you try to change it with the defineProperty function, it causes an error. An example to see better would be to wrap the code in a closure function. This way the windowProperty defined by the var is not the same and everything is ok.

(function () {
    var windowProperty;
    Object.defineProperty(...);
    //It works because the previously defined variable is in the scope of the function and thus is not the same as window.windowProperty.
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM