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

前端 未结 7 1282
故里飘歌
故里飘歌 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:10

    As pointed out by others yes you can and yes it means adding "global variables".

    Having global variables is not best practice but sometimes it is the simplest thing to do. For instance if you use IFrames and want the child-window to access some property of the parent window. Such a property must be "global" for a child to access it. But this also shows that it is not "truly global", it is just a property of a specific window. But it can conflict with other property-names such as names of functions defined in the same window, perhaps by some libraries you use.

    So we know global variables are bad. If we decide to use them anyway is there anything we can do to minimize their badness?

    Yes there is: Define a SINGLE global variable with a more or less unique name, and store an OBJECT into it. Store all other "variables" you need as fields of that single object.

    This way you don't need to ever add more than a single global variable (per window). Not TOO bad.

    Name it more or less uniquely so it is unlikely to conflict with anybody else's single global. For instance you could use your name + 's' as the variable name:

    window.Panus  = {}; 
    

    :-)

提交回复
热议问题