JavaScript中的全局函数 [英] Global functions in javascript

查看:96
本文介绍了JavaScript中的全局函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对js很陌生,想要了解全球和私人功能。我了解全球和地方变数。但是如果我有一个名为test.html的html和一个名为test1.js& amp; 2的js文件, test2.js。现在我包含test1.js& test.html中的test2.js,并在test1.js和test.html中调用test2.js中编写的函数。

我在test2.js中编写的函数是这种形式的函数:
$ b

function abc(){。 ..}



函数pqr(){...}等。

以上函数是全局函数吗?如果他们是,我怎么能让他们全球化,仍然访问他们在test1.js和test.html?



因为我已阅读全局函数或全局变量是坏对吗?

解决方案

JS中的所有内容都必须包含范围。因此,如果你直接在文件中定义函数,它将被绑定到 window 对象,即它将是全局的。

为了使其成为私人,您必须创建一个包含这些功能的对象。你认为乱抛垃圾的全局范围是错误的,但你必须将全局范围内的东西放在全局范围才能访问它,JS库也是这样做的,没有其他的解决方法。但考虑一下你在全局范围内放置的东西,单个对象应该足够用于你的库。



示例:

  MyObject = {
abc:function(...){...},
pqr:function(...){。 ..}
//其他函数...
}

致电 abc 在某处,可以是同一个文件或其他文件:

  MyObject名为.abc(...); 


I'm new to js and trying to understand global and private functions. I understand global and local variables. But if I have an html named test.html and a 2 js files named test1.js & test2.js. Now I include the test1.js & test2.js in test.html and call the functions written in test2.js inside test1.js and test.html.

The functions that I have written in test2.js are in this form

function abc(){...}

function pqr(){...} etc.

are these above functions global? If they are , how can I not make them global and still access them in test1.js and test.html?

As I have read global functions or global variables are bad right?

解决方案

Everything in JS is bound to containing scope. Therefore, if you define a function directly in file, it will be bound to window object, i.e. it will be global.

To make it "private", you have to create an object, which will contain these functions. You are correct that littering global scope is bad, but you have to put something in global scope to be able to access it, JS libraries do the same and there is no other workaround. But think about what you put in global scope, a single object should be more than enough for your "library".

Example:

MyObject = {
    abc: function(...) {...},
    pqr: function(...) {...}
    // other functions...
}

To call abc for somewhere, be it same file or another file:

MyObject.abc(...);

这篇关于JavaScript中的全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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