【问题标题】:variable named undefined in Javascript Libraries [duplicate]Javascript库中未定义的变量[重复]
【发布时间】:2011-07-06 14:35:10
【问题描述】:

可能的重复:
How does this JavaScript/JQuery Syntax work: (function( window, undefined ) { })(window)?
What advantages does using (function(window, document, undefined) { … })(window, document) confer?

我看到很多 javascript 库创建了一个名为“undefined”的变量,我无法弄清楚它的用途,下面是从 jQuery 库复制的行

 * Date: Wed Feb 23 13:55:29 2011 -0500
 */
(function( window, undefined ) {

// Use the correct document accordingly with window argument (sandbox)
var document = window.document;
var jQuery = (function() {

请告诉我这样做的原因和好处!!

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你会看到是这样的:

    (function(undefined) {
        /* lots of code */
    }());
    

    这会创建一个匿名函数并立即执行它。该函数有一个名为undefined 的参数。由于没有传递给函数的参数,因此变量undefined实际上是Javascript primitive value undefined

    那么你为什么要这样做呢?好吧,问题是您实际上可以创建一个名称为 undefined 的变量并将其设置为您喜欢的任何内容,例如:

    var undefined = 'some text';
    

    您的代码中的测试myvalue === undefined 会产生意想不到的结果。

    带有名为undefined 的参数的匿名函数基本上将undefined 的值“重置”为原始值,因此您可以根据需要检查它,而不必担心它是否具有正确的值。

    【讨论】:

      【解决方案2】:

      确保undefined 实际上是undefinedPaul Irish calls it the asshole effect,页面中包含的其他js可能会改变undefined的含义,然后你会得到意想不到的结果。

      【讨论】:

      • 我一直不太明白。我也可以做一些傻事,比如jQuery = {},然后 jQuery 就会停止工作——这并不奇怪。如果你想通过输入undefined = true 来打自己的脚,为什么要阻止你?
      • 好吧,其他人可能会尝试朝你的脚开枪,就像你包含的随机插件一样。
      猜你喜欢
      • 2016-12-26
      • 1970-01-01
      • 2013-04-28
      • 2020-04-25
      • 1970-01-01
      • 2022-01-03
      • 2019-09-29
      • 2014-12-05
      • 1970-01-01
      相关资源
      最近更新 更多