Javascript 我可以在javascript中向'window'对象添加属性吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12743007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:09:27  来源:igfitidea点击:

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

javascriptcross-browser

提问by akkishore

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

我可以在javascript中向'window'对象添加任何随机属性吗?就像是:

window.my_own_attr = "my_value"

Does it have any side effects with any libraries? And is it cross-browser compatible?

它对任何库有任何副作用吗?它是否跨浏览器兼容?

回答by James Allardice

Can I add any random attribute to 'window' object in javascript?

我可以在javascript中向'window'对象添加任何随机属性吗?

Yes, just like you've shown.

是的,就像你展示的那样。

Does it have any side effects with any libraries?

它对任何库有任何副作用吗?

No, not unless you use a library which sets a property you then overwrite.

不,除非您使用设置属性然后覆盖的库。

And is it cross-browser compatible?

它是否跨浏览器兼容?

Yes, completely.

是的,完全。



Having said that, this practice is generally frowned upon. You could end up overwriting something you don't want to.

话虽如此,这种做法通常是不受欢迎的。你最终可能会覆盖一些你不想要的东西。

回答by KooiInc

In all browsers, windowis 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.

所有浏览器中window都是 javascript 全局命名空间。每个属性或方法都“存在”于该命名空间中。因此,如果您将一个属性分配给window,它实际上是一个全局变量

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 JQueryframework, the JQuerynamespace will be replaced by your assignment, rendering it useless.

您必须谨慎使用 javascript 框架。例如,如果您声明window.JQuery并使用JQuery框架,JQuery命名空间将被您的赋值替换,使其变得无用。

回答by Alnitak

Yes, you can, but in general you shouldn't.

是的,你可以,但一般来说你不应该。

The windowobject is also the JS default "global" object, so all global variables get added there.

window对象也是 JS 默认的“全局”对象,因此所有全局变量都会添加到那里。

You're unlikely to break anything unless you overwrite a property that's already there, but it's considered bad practise to dump variables on window, or otherwise create lots of global variables.

除非覆盖已经存在的属性,否则不太可能破坏任何内容,但将变量转储到 上window或以其他方式创建大量全局变量被认为是不好的做法。

回答by Sam Rahimi

I won't repeat what others have said re: the hackyness of this practice. But it can be incredibly useful when using a rigid framework like Angular mixed with vanilla HTML / JS (or jQuery) code. Which is also hacky and frowned upon, but sometimes there are good reasons, like if you have lots of pre-existing JS code that will be challenging to integrate into the framework.

我不会重复其他人所说的:这种做法的笨拙。但是当使用像 Angular 这样的刚性框架与普通 HTML / JS(或 jQuery)代码混合时,它会非常有用。这也很老套和不受欢迎,但有时有很好的理由,比如如果你有很多预先存在的 JS 代码,将很难集成到框架中。

The more interesting question to me is HOW to make use of the ability to add properties to the global windowobject. There is a pattern I use when I want to expose the methods of an Angular provider (service) to code that otherwise would be unable to inject the service, probably because it runs outside of the Angular DI framework. The way I do it is as follows:

对我来说更有趣的问题是如何利用向全局window对象添加属性的能力。当我想将 Angular 提供者(服务)的方法公开给无法注入服务的代码时,我使用了一种模式,这可能是因为它在 Angular DI 框架之外运行。我的做法如下:

  1. Define your service as a provider in your top level module.
  2. In the constructor or onInit of app.component.js (or whatever your top level component is that imports the provider), inject the provider normally, perform any one time initialization that it needs, and then call window['MyServiceName'] = this
  1. 在顶级模块中将您的服务定义为提供者。
  2. 在 app.component.js 的构造函数或 onInit(或任何导入提供程序的顶级组件)中,正常注入提供程序,执行它需要的任何一次初始化,然后调用 window['MyServiceName'] = this

Assuming you have designed the provider to follow a Singleton pattern, your provider's methods can now be safely called from anywhere. A non-Angular script need simply call window['MyServiceName'].methodName()

假设您已将提供程序设计为遵循单例模式,您的提供程序的方法现在可以从任何地方安全地调用。非 Angular 脚本只需调用window['MyServiceName'].methodName()

回答by Kernel James

In IE if an element has an id, then that node is accessible on the window object as a property:

在 IE 中,如果元素具有 id,则该节点可作为属性在 window 对象上访问:

<div id="num"></div>

<div id="num"></div>

alert(num); //Element

alert(num); //Element

num = 3; //throws exception

num = 3; //throws exception

var num = 3; //ok

var num = 3; //ok

回答by Riz

That 'll work fine, no conflict with any library until used same variable name, will work in all browsers, but not recommended as this will create global JS variable.

这会正常工作,在使用相同的变量名之前不会与任何库发生冲突,将在所有浏览器中工作,但不推荐,因为这将创建全局 JS 变量。

回答by Panu Logic

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.

拥有全局变量不是最佳实践,但有时这是最简单的做法。例如,如果您使用 IFrame 并希望子窗口访问父窗口的某些属性。这样的属性必须是“全局”的,孩子才能访问它。但这也表明它不是“真正的全局”,它只是特定窗口的属性。但它可能与其他属性名称冲突,例如在同一窗口中定义的函数名称,可能是您使用的某些库。

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.

是的,有:定义一个或多或少具有唯一名称的 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:

或多或少地为它命名,这样它就不太可能与任何其他人的单一全局冲突。例如,您可以使用您的姓名 + 's' 作为变量名:

window.Panus  = {}; 

:-)

:-)