gpt4 book ai didi

javascript - (function($) { })(jQuery) 的含义(例如,在 jQuery Enlightenment 书中)

转载 作者:行者123 更新时间:2023-12-03 11:41:05 25 4
gpt4 key购买 nike

我喜欢《DOM 启蒙》这本书,并且想阅读 jQuery 的姊妹篇。 .

我之前使用过基本的jquery,如下所示,我理解它们..

$(document).bind(‘contextmenu’, function() {
// do something
});

但是书中提到了如下内容......我不明白它是如何使用的?

(function($){
// Use $ alias worry-free of conflicts
alert('You are using jQuery ' + $().jquery );
})(jQuery)

最佳答案

console = $('#console');
console.append("<p>At the start of execution, does $ === jQuery? " +( ($ === jQuery)?"yes":"no")+ "</p>");
$ = function() {};
console.append("<p>After re-assignment, does $ === jQuery? " +( ($ === jQuery)?"yes":"no")+ "</p>");
(function($) {
console.append("<p>Inside our IFFE, does $ === jQuery? " +( ($ === jQuery)?"yes":"no")+ "</p>");
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="console"></div>

这是一个“立即调用函数表达式”——有时称为“IIFE”('iffy');您将全局对象 jQuery 传递到 IIFE 中,它在其中绑定(bind)到名称 $ - 以防万一加载的其他脚本使用 $ 出于其自身目的。

看到有人使用相同的技术确保“未定义”没有被重新定义为除 ECMAScript undefined 之外的其他内容也并不罕见:

(function($, undefined) {
// first argument, the global 'jQuery', bound to $
// there is no second argument, so the ECMAScript built-in type 'undefined'
// will be bound here to the name 'undefined'.
})(jQuery);

关于javascript - (function($) { })(jQuery) 的含义(例如,在 jQuery Enlightenment 书中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26270071/

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