問(wèn)題描述
jQuery 網(wǎng)站列出了 jQuery 的基本插件語(yǔ)法,如下所示:
The jQuery site lists the basic plugin syntax for jQuery as this:
(function( $ ){
$.fn.myPlugin = function() {
// there's no need to do $(this) because
// "this" is already a jquery object
// $(this) would be the same as $($('#element'));
this.fadeIn('normal', function(){
// the this keyword is a DOM element
});
};
})( jQuery );
我只是想從 Javascript 的角度了解那里發(fā)生了什么,因?yàn)樗雌饋?lái)不像我以前見(jiàn)過(guò)的 JS 的任何語(yǔ)法.所以這是我的問(wèn)題清單:
I'd just like to understand what is going on there from Javascript's point of view, because it doesn't look like it follows any syntax I've seen JS do before. So here's my list of questions:
如果你將 function($)... 替換為一個(gè)變量,比如the_function",語(yǔ)法如下:
If you replace function($)... with a variable, say "the_function", the syntax looks like this:
(the_function)( jQuery );
什么是(jQuery);"正在做?the_function 周?chē)睦ㄌ?hào)真的有必要嗎?他們?yōu)槭裁丛谀抢?有沒(méi)有其他類似的代碼可以提供?
What is "( jQuery );" doing? Are the parenthesis around the_function really necessary? Why are they there? Is there another piece of code you can give that is similar?
它以函數(shù)($)開(kāi)頭.所以它正在創(chuàng)建一個(gè)函數(shù),據(jù)我所知,它永遠(yuǎn)不會(huì)運(yùn)行,帶有 $ 的參數(shù),它已經(jīng)定義了?那里發(fā)生了什么?
It begins with function( $ ). So it's creating a function, that as far as I can tell will never be run, with the parameter of $, which is already defined? What is going on there?
感謝您的幫助!
推薦答案
function(x){
x...
}
只是一個(gè)沒(méi)有名字的函數(shù),它接受一個(gè)參數(shù)x",并用 x 做事.
is just a function without a name, that takes one argument, "x", and does things with x.
您可以使用 $ 代替常見(jiàn)的變量名x",這是一個(gè)不太常見(jiàn)的變量名,但仍然合法.
Instead of 'x', which is a common variable name, you can use $, which is a less common variable name, but still legal.
function($){
$...
}
我將它放在括號(hào)中以確保它被解析為表達(dá)式:
I'll put it in parentheses to make sure it parses as an expression:
(function($){
$....
})
要調(diào)用一個(gè)函數(shù),你可以在它后面加上一個(gè)參數(shù)列表 ().例如,如果我們想調(diào)用這個(gè)函數(shù),傳入 3 作為 $
的值,我們可以這樣做:
To call a function, you put () after it with a list of arguments. For example, if we wanted to call this function passing in 3 for the value of $
we would do this:
(function($){
$...
})(3);
只是為了好玩,讓我們調(diào)用這個(gè)函數(shù)并將 jQuery 作為變量傳遞:
Just for kicks, let's call this function and pass in jQuery as a variable:
(function($){
$....
})(jQuery);
這將創(chuàng)建一個(gè)新函數(shù),該函數(shù)接受一個(gè)參數(shù),然后調(diào)用該函數(shù),傳入 jQuery 作為值.
This creates a new function that takes one argument and then calls that function, passing in jQuery as the value.
為什么?
- 因?yàn)槊看文阆胗?jQuery 做某事時(shí)都寫(xiě) jQuery 很乏味.
為什么不直接寫(xiě) $ = jQuery
?
- 因?yàn)槠渌丝赡芤褜?$ 定義為其他含義.這保證了 $ 的任何其他含義都被這個(gè)所掩蓋.
這篇關(guān)于我想了解 jQuery 插件語(yǔ)法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!