如何从不同的js文件中访问可观察变量 [英] how to access observable variable from different js files

查看:104
本文介绍了如何从不同的js文件中访问可观察变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有3个JS文件。

i想要创建一个全局可观察变量,我可以从任何现有的JS文件访问和更新它。



请帮我一个方法。

i have 3 JS files in my project.
i wanted to create a global observable variable where i can access and update it from any of my existing JS files.

Please help me with a way to do this.

推荐答案

首先,从JavaScript代码的角度来看,没有不同的文件。您在HTML中包含多个文件,并按照它们包含的顺序进行处理,就像它是一个文件一样。所以,关于不同文件的问题根本没有意义。如果你的对象是全局的,它将是所有文件中的全局对象,同一个。



同时,使用全局对象是一个非常糟糕的主意。您应该更好地考虑如何将更多对象作为本地对象,以及如何在本地上下文中传递它们,这可以使用函数参数来完成,包括this。



-SA
First of all, from the standpoint of JavaScript code, there are no "different files". You include more then one file in HTML, and they are processed in the order they are included, as if it was one single file. So, the question about "different files" simply makes no sense. If your object is global, it will be global object in all files, the same one.

At the same time, using global objects is a pretty bad idea. You should better think at how to make more objects as local as possible, and how to pass them in local contexts, which can be done using function argument, including "this".

—SA


这篇关于如何从不同的js文件中访问可观察变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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