在JavaScript'窗口'对象中存储变量是使用该对象的正确方法? [英] Storing a variable in the JavaScript 'window' object is a proper way to use that object?

查看:98
本文介绍了在JavaScript'窗口'对象中存储变量是使用该对象的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(也许)我刚刚解决了我的问题(如何更新前端内容之后,窗体从对话窗口成功提交)通过存储/保存一个变量在JavaScript 窗口对象。但是,由于我是JavaScript的新手,所以如果在JavaScript 窗口中存储/保存变量对象是一个常见的/正确的使用该对象的方式。是吗?

(Maybe) I just solved a my problem (How to update front-end content after that a form is successfully submitted from a dialog window?) by "storing" / "saving" a variable in the JavaScript window object. However, since I am newbie in JavaScript matters, I have some doubts if storing / saving a variable in the JavaScript window object is a "common" / "proper" way to use that object. Is it?

例如,使用以下代码

$('.trigger').click(function() {
  window.trigger_link = this;
});

是否可取?

推荐答案

在JavaScript中,任何全局变量实际上是窗口对象的属性。使用一个等价于(和可互换)使用另一个。

In JavaScript, any global variable is actually a property of the window object. Using one is equivalent to (and interchangeable with) using the other.

使用全局变量当然是常见的,所以问题是它是否正确。 通常,不鼓励全局变量,因为可以从任何功能访问它们,并且冒着尝试从写入相同的变量。 (任何环境中的任何编程语言都不是JavaScript)。

Using global variables is certainly "common," so the question is whether or not it's "proper." Generally, global variables are discouraged, because they can be accessed from ANY function and you risk having multiple functions trying to read from and write to the same variables. (This is true with any programming language in any environment, not just JavaScript.)

通过创建您的应用程序唯一的命名空间。最简单的方法是创建一个具有唯一名称的全局对象,将变量作为该对象的属性:

Solve this problem by creating a namespace unique to your application. The easiest approach is to create a global object with a unique name, with your variables as properties of that object:

var window.MyLib = {}; // global Object container
MyLib.value = 1;
MyLib.increment = function() { MyLib.value++; }
MyLib.show = function() { alert(MyLib.value); }

MyLib.value=6;
MyLib.increment();
MyLib.show(); // alerts 7






另一种方法是使用< a href =http://api.jquery.com/data =nofollow noreferrer> .data() 将变量附加到相关DOM元素。这在所有情况下都是不实际的,但是在全局名称空间中不存在可以全局访问的变量是很好的方式。


Another approach is to use .data() to attach variables to a relevant DOM element. This is not practical in all cases, but it's a good way to get variables that can be accessed globally without leaving them in the global namespace.

这篇关于在JavaScript'窗口'对象中存储变量是使用该对象的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆