窗口上的Javascript getters/ssetters

Javascript getters/setters on window

本文关键字:ssetters getters Javascript 窗口      更新时间:2023-09-26

为什么下面的代码在firefox21.0中抛出TypeError?

Object.defineProperty(window,'windowProperty',{
    get: function(){
        return 'windowProperty'
    },
    set: function(val){
        console.log('windowProperty is being set');
    },
    configurable: true,
});
var windowProperty;

但是在不使用var的情况下声明windowProperty有效:

windowProperty;

window.windowProperty;

这种行为也出现在蜘蛛侠身上:

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

只写

windowProperty;

不声明变量。它只是尝试在最接近的上下文中返回变量内容,如果找不到,则返回undefined。这就像一项没有目标的任务。例如,您也可以在不抛出错误的情况下编写随机文本:

'Hello, world !';
123456;
undefined;

相反,使用var试图重新定义之前在代码中已经定义的属性,因此会出现错误。

编辑
正如simonzack所说,浏览器在重新定义变量时并不总是发送错误。例如:

var test; var test;

不会抛出这个错误(即使这是个坏主意,一些JS验证器会警告你) 然而,通过定义getter和setter,浏览器会"锁定"此属性(例如,为了防止冲突,同一属性上有两个不同的setter) 我的错,这是一种误解。

你想重新定义你的变量有什么原因吗?

编辑2
考虑到var声明在defineProperty之前,这使得我的解释更加精确。实际上,当您第一次使用var声明时,浏览器会将其configurable状态设置为false,从而阻止对其描述符进行更改(请参阅链接)。因此,当您尝试使用defineProperty函数更改它时,会导致错误。一个更好的例子是将代码封装在闭包函数中。这样一来,var定义的windowProperty就不一样了,一切都很好

(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.
})();