gpt4 book ai didi

module - 如何将 noConflict 添加到 JS 模块模式?

转载 作者:行者123 更新时间:2023-12-01 08:26:09 26 4
gpt4 key购买 nike

我在 JS 中使用以下模式:

var lib =
{
module_one:
{
init: function () {
...
}
},
module_two:
{
init: function () {
...
}
}
};

问题是,添加的最佳方式是什么:

(function ($) {          
...
})(jQuery);

我尝试将它放在 var lib 周围,但这不起作用。将其添加到每个函数中是可行的,但似乎有点困惑..?

是否可以以某种方式将其添加到 init: function($) 中?

对于 jQuery 来说相当新,所以如果您对此模式有任何其他建议,请告诉我:-)

最佳答案

基本上,你可以这样做:

(function() {
var global, lib, oldlib;

// We call this anonymous scoping function directly, so we know that
// within it, `this` is the JavaScript global object. Grab a
// local reference to it so we can use it within functions that get
// called via dotted notation and so have different `this` values.
global = this;

// Remember any value that already exists for the `lib` property
// of the global
oldlib = global.lib;

// Define our lib, assigning it to a local variable
lib = {
/* ...your stuff as usual, plus: */

noConflict: function() {
global.lib = oldlib;
return lib;
}
};

// Publish our lib externally on the global object
global.lib = lib;
})();

...然后可以像这样使用:

var alias = lib.noConflict();

其工作原理如下:

  1. 我们定义一个作用域函数,然后立即调用它。
  2. 在作用域函数中,我们将 this 值获取为名为 global 的变量。由于我们调用作用域函数的方式,这将是 JavaScript 全局对象。 (浏览器上的全局对象是 window,但无需将其限制于浏览器,因此可以通过这种方式获取 global)。
  3. 我们要做的第一件事是将全局对象的 lib 属性拥有的所有旧值保存在我们的作用域函数中名为 oldlib 的局部变量中。
  4. 我们为 lib 设置了新值。
  5. 我们的 noConflict 函数恢复 lib 属性的早期值,并返回我们的 lib 引用,以便其他人可以将其用作别名。

顺便说一句,当您使用作用域函数时,您还可以切换到使用命名函数而不是匿名函数,这 has several benefits 。以下内容已更新为使用命名函数来实现 noConflict

(function() {
var global, lib, oldlib;

// We call this anonymous scoping function directly, so we know that
// within it, `this` is the JavaScript global object. Grab a
// local reference to it so we can use it within functions that get
// called via dotted notation and so have different `this` values.
global = this;

// Remember any value that already exists for the `lib` property
// of the global
oldlib = global.lib;

// Define the functions for our lib. Because they're defined
// within our scoping function, they're completely private
function lib_noConflict() {
global.lib = oldlib;
return lib;
}

// Define our lib, publishing the functions we want to be public
lib = {
/* ...your stuff as usual, plus: */

noConflict: lib_noConflict
};

// Publish our lib externally on the global object
global.lib = lib;
})();

关于module - 如何将 noConflict 添加到 JS 模块模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3666586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com