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

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

问题描述

(也许)我刚刚解决了我的问题(如何在从对话框窗口成功提交表单后更新前端内容?) 通过在 JavaScript 窗口中存储"/保存"一个变量 对象.但是,由于我是 JavaScript 方面的新手,我怀疑在 JavaScript window 对象中存储/保存变量是否是使用该对象的常见"/正确"方式.是吗?

(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 中,任何全局变量实际上都是 window 对象的一个​​属性.使用一个等同于(并且可以互换)使用另一个.

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:

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

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

<小时>

另一种方法是使用 .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 'window' 对象中存储变量是使用该对象的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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