包含外部 jQuery 脚本

发布于 2024-11-14 18:59:39 字数 365 浏览 8 评论 0原文

我有一个外部 JavaScript 文件,将在包含许多其他脚本的页面上使用。我的脚本涉及大量侦听事件的 jQuery,并且根据设计,我声明了许多全局变量。我一直在阅读最佳实践文章,其中有很多关于“污染全局命名空间”和无意的脚本交互的说法。

封闭(封装?)我的 JavaScript 文件的最佳方法是什么,以便:

  • 我仍然可以访问某些 封装之外的变量
  • jQuery 事件侦听器将 功能正常

我不能随意透露代码,所以即使是一般性的回应也是值得赞赏的。此外,欢迎提供有关使脚本不易受到页面上其他脚本攻击的任何其他提示。

我已经找到了常规 JavaScript 的封装样式,但是使用 jQuery 会使情况变得复杂吗?

I have an external JavaScript file that will be used on pages with lots of other scripts. My script involves a lot of jQuery that listens for events, and by design, I have many global vars declared. I've been reading best practice articles, and a lot is said about 'polluting the global namespace' and inadvertent script interaction.

What's the best way to enclose (encapsulate?) my JavaScript file so that:

  • I can still access some of the
    variables outside of the enclosure
  • The jQuery event listeners will
    function properly

I'm not at liberty to disclose the code, so even general responses are appreciated. Additionally, any other tips on making scripts less vulnerable to other scripts on the page are welcome.

I've found enclosure styles for regular JavaScript, but does the use of jQuery complicate this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

新雨望断虹 2024-11-21 18:59:39

一般来说,这可以归结为将对象封装到“命名空间”中。我在那里使用引号是因为该术语不是 JavaScript 中的官方语义,而是通过基本对象封装实现的语义。

有多种方法可以做到这一点,最终取决于个人喜好。

一种方法是只使用一个基本的 JS 对象,并将所有内容保留在其中。对象的名称应该是语义的,并赋予对象一些含义,但否则它的目的只是包装您自己的代码并将其保留在全局命名空间之外。

var SomeName = {
    alpha: 1,
    beta: {a: 1, b: 2},
    gamma: function(){ 
        SomeName.alpha += 1;
    }
}

在这种情况下,只有 SomeName 位于全局命名空间中。这种方法的一个缺点是命名空间内的所有内容都是公共的,并且您必须使用完整的命名空间来引用对象,而不是使用“this” - 例如,在 SomeName.gamma 中,我们必须使用 SomeName.alpha 来引用阿尔法的内容。

另一种方法是使命名空间成为具有属性的函数。这种方法的一个好处是您可以通过闭包创建“私有”变量。它还允许您访问闭包函数和变量,而无需完整的命名空间引用。

var SomeName = (function(){
   var self = this;
   var privateVar = 1;
   var privateFunc = function() { };   

   this.publicVar = 2;
   this.publicFunc = function(){
       console.log(privateVar);
       console.log(this.publicVar); // if called via SomeName.publicFunc

       setTimeout(function(){ 
           console.log(self.publicVar);
           console.log(privateVar);
       }, 1000);
   };
}();

这种方法的另一个好处是它可以让您保护您想要使用的全局变量。例如,如果您使用 jQuery 和另一个创建 $ 变量的库,那么通过这种方法,您始终可以确保在使用 $ 时引用 jQuery:

var SomeName = (function($){
    console.log($('div'));
})(jQuery);

Generally what this boils down to is encapsulating your objects into a "namespace". I use quotes there because the term is not an official semantic in JavaScript, but rather one that is achieved through basic object encapsulation.

There are several ways to do this, and it ultimately comes down to personal preference.

One approach is to just use a basic JS object, and keep everything in it. The name of the object should be semantic and give the object some meaning, but otherwise it's purpose is to just wrap your own code and keep it out of the global namespace.

var SomeName = {
    alpha: 1,
    beta: {a: 1, b: 2},
    gamma: function(){ 
        SomeName.alpha += 1;
    }
}

In this case, only SomeName is in the global namespace. The one downside to this approach is that everything inside the namespace is public, and you have to use the full namespace to reference an object, instead of using 'this' - e.g. in SomeName.gamma we have to use SomeName.alpha to reference the contents of alpha.

Another approach is to make your namespace a function with properties. The nice feature of this approach is you can create 'private' variable through closures. It also gives you access to closured functions and variables without full namespace referencing.

var SomeName = (function(){
   var self = this;
   var privateVar = 1;
   var privateFunc = function() { };   

   this.publicVar = 2;
   this.publicFunc = function(){
       console.log(privateVar);
       console.log(this.publicVar); // if called via SomeName.publicFunc

       setTimeout(function(){ 
           console.log(self.publicVar);
           console.log(privateVar);
       }, 1000);
   };
}();

The other bonus of this approach is it lets you protect the global variables you want to use. For example, if you use jQuery, AND another library that creates a $ variable, you can always insure you are referencing jQuery when using $ by this approach:

var SomeName = (function($){
    console.log($('div'));
})(jQuery);
萤火眠眠 2024-11-21 18:59:39

一种方法是像这样命名空间:

var MyNamespace = {
    doSomething: function() {},
    reactToEvent: function() {},
    counter: 0
}

您只需使用命名空间引用函数或变量:MyNamespace.reactToEvent。这对于分离通常在窗口(所有对抗都在其中)中的内容非常有效。

One method is to namespace like this:

var MyNamespace = {
    doSomething: function() {},
    reactToEvent: function() {},
    counter: 0
}

You will just have to refer to the functions or variable using the namespace: MyNamespace.reactToEvent. This works fine for separating what you would normally have in the window (where all the confrontation is).

涫野音 2024-11-21 18:59:39

您可以将代码包装在匿名 Javascript 函数中,并且只返回您想要向外界公开的内容。您需要在全局变量前添加 var 前缀,以便它们仅保留在匿名函数的范围内。像这样:

var myStuff = (function() {

   var globalVar1;
   var globalVar2;
   var privateVar1;

   function myFunction() {
     ...
   }

   function myPrivateFunction() {
     ...
   }

   return {
      var1: globalVar1,
      var2: globalVar2,
      myFunction: myFunction
   };

})();

现在您可以访问 myStuff.var1myStuff.myFunction()

You can wrap your code in an anonymous Javascript function and only return what you want to expose to the outside world. You will need to prefix var to your global variables so that they remain only in the scope of the anonymous function. Something like this:

var myStuff = (function() {

   var globalVar1;
   var globalVar2;
   var privateVar1;

   function myFunction() {
     ...
   }

   function myPrivateFunction() {
     ...
   }

   return {
      var1: globalVar1,
      var2: globalVar2,
      myFunction: myFunction
   };

})();

Now you can access myStuff.var1 and myStuff.myFunction().

陈甜 2024-11-21 18:59:39

封装或限制命名空间污染的两种方法

1) 创建一个全局变量并将您需要的所有内容填充到其中。

var g = {};
g.somevar = "val";
g.someothervar = "val2";
g.method1 = function() 
{
   // muck with somevar
   g.somevar = "something else";
};

2) 对于内联脚本,考虑限制调用函数的范围。

<script>
(  
   function(window)
   {
      // do stuff with g.somevar
      if(g.somevar=="secret base")
        g.docrazystuff();      

   }
)();  // call function(window) then allow function(window) to be GC'd as it's out of scope now
</script>

Two ways to encapsulate or limit namespace pollution

1) Create one global var and stuff everything you need into it.

var g = {};
g.somevar = "val";
g.someothervar = "val2";
g.method1 = function() 
{
   // muck with somevar
   g.somevar = "something else";
};

2) For inline scripts, consider limiting the scope of the functions called.

<script>
(  
   function(window)
   {
      // do stuff with g.somevar
      if(g.somevar=="secret base")
        g.docrazystuff();      

   }
)();  // call function(window) then allow function(window) to be GC'd as it's out of scope now
</script>
夜声 2024-11-21 18:59:39

我刚刚开始使用 RequireJS 现在已经对它着迷了。

它基本上是一个模块化 JavaScript 格式的依赖管理系统。通过这样做,您几乎可以消除将任何内容附加到全局命名空间的情况。

好处是您只在页面 require.js 上引用一个脚本,然后告诉它首先运行哪个脚本。从那里开始,一切都变得神奇了......

这是一个示例实现脚本:

require([
   //dependencies
   'lib/jquery-1.6.1'
], function($) {
   //You'll get access to jQuery locally rather than globally via $


});

通读 RequireJS API 并看看这是否适合您。我现在所有的剧本都是这样写的。这很棒,因为在每个脚本的顶部,您可以确切地知道您的依赖项类似于服务器端语言 - Java 或 C#。

I just started using RequireJS and have now become obsessed with it.

It's basically a dependency management system in a modular JavaScript format. By doing so you can virtually eliminate attaching anything to the global namespace.

What's nice is that you only reference one script on your page require.js then tell it what script to run first. From there it is all magic...

Here's an example implementation script:

require([
   //dependencies
   'lib/jquery-1.6.1'
], function($) {
   //You'll get access to jQuery locally rather than globally via $


});

Read through the RequireJS API and see if this is right for you. I'm writing all my scripts like this now. It's great because at the top of each script you know exactly what you dependencies are similar to server-side languages - Java or C#.

戏舞 2024-11-21 18:59:39

这是 jQuery 插件的常见做法,原因与您提到的相同:

;(function ($) {

    /* ... your code comes here ... */

})(jQuery);

这是一个即时函数。如果您在内部声明“全局”变量,它们将是该闭包的本地变量(对于您在内部创建的代码仍然是“全局”的)。您的事件侦听器也将在此处工作,并且您仍然能够访问真正的全局变量。

This is a common practice with jQuery plugins for the same reasons you mention:

;(function ($) {

    /* ... your code comes here ... */

})(jQuery);

This is an immediate function. If you declare your "global" variables inside, they will be local to this closure (still "global" for the code you create inside). Your event listeners will work inside here too, and you will still be able to reach real global variables.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文