Can I add attributes to 'window' object in javascript?

前端 未结 7 1265
故里飘歌
故里飘歌 2020-12-13 18:02

Can I add any random attribute to \'window\' object in javascript? Some thing like:

window.my_own_attr = \"my_value\"

Does it have any side

7条回答
  •  北海茫月
    2020-12-13 18:07

    In all browsers, window is the javascript global namespace. Every property or method 'lives' in that namespace. So if you assign a property to window, it is in effect a global variable.

    example:

    window.myConstant = 5;
    
    function multiply(val){
      return myConstant * (val || 1);
    }
    multiply(10); //=> 50
    multiply(); //=> 5
    

    You have to be cautious with javascript frameworks. For instance, if you declare window.JQuery, and use the JQuery framework, the JQuery namespace will be replaced by your assignment, rendering it useless.

提交回复
热议问题