Is it possible to overwrite the undefined in javascript?

后端 未结 3 833
萌比男神i
萌比男神i 2021-01-02 14:02

like

function myFunction(){
    var undefined = \"abc\";
}

If its possible then how to restrict not to allow that?

相关标签:
3条回答
  • 2021-01-02 14:34

    Yes it is possible to overwrite undefined.

    This question has good solutions for working around that problem - How to check for "undefined" in JavaScript?

    0 讨论(0)
  • 2021-01-02 14:43

    Some browsers allow it, the best way to restrict it is avoiding it.

    But... some are using this technique to preserve the undefined:

    (function(undefined){
    
    })()
    

    They get a variable called undefined but don't pass a value which gives undefined the undefined value.

    From jQuery's source code:

    (function( window, undefined ) {
        ...
        ...
    })(window);
    
    0 讨论(0)
  • 2021-01-02 14:48

    Is it possible to overwrite the undefined in javascript?

    If by "the undefined" you mean the global undefined variable, then no. Since EcmaScript 5, it is specified as non-writable. However, older browsers don't adhere that spec, so it is overwritable in legacy engines. You cannot really prevent it in them, but always reset it by undefined = void 0;. If you still worry and want to know how to protect your own scripts, check the question How dangerous is it in JavaScript, really, to assume undefined is not overwritten?.

    like function myFunction(){ var undefined = "abc"; }

    That's a different thing. You can always declare a local variable with the name undefined (shadowing the global one) and assign arbitrary values to it.

    0 讨论(0)
提交回复
热议问题