您的位置:首页 > Web前端 > JavaScript

js匿名函數

2016-01-20 17:34 441 查看
(function($){})(jquery) == (function($){})(jQuery)

实际上是匿名函数

用于存放开发插件的代码

作用(非常有用):

这种写法的最大好处是形成闭包。在(function($) {…})(jQuery)在内部定义的函数和变量只能在此范围内有效。

形成是否函数函数、私有变量的概念。比如:

var i=3;

function init(){

alert("外层init:"+i);

}

(function($) {

var i=2;

function init(){

alert("内层init:"+i);

}

init();

})(jQuery);

init();

执行结果:

内层init:2

外层init:3

以下是一個實驗的例子

<script src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">

//(function ($) {
// alert(1);
// $.a = function (i)
// {
// alert(i.name);
// this.shows = function (j)
// {
// alert(j);
// alert(3);
// abc();
// def();
// }
// abc = function ()
// {
// alert(4);
// }
// def = function ()
// {
// i.callBack(666666);
// }
// }
//})($);
//var i = new $.a({
// name:"sdy",
// callBack: function (no)
// {
// alert(no);
// alert(1234);
// }
//});
//i.shows(123);

function MM($) {
alert(2);
$.a = function (i) {
alert(i.name);
this.shows = function (j) {//this為必須寫的
alert(j);
alert(1);
cc();
}
aa = function () {
alert("aa");
}
bb = function () {
alert("bb");
}
cc = function ()
{
i.callBank("回調函數");//回調函數 callBack 寫錯也沒事 哈哈哈哈
}
}
};
MM(jQuery);
var abc = new $.a({
name: "sdy", callBank: function (no)
{
alert(no);
}
});
abc.shows(1);
//(function ($) {
// alert(1);
// alert($);
//})(jQuery);

//function MM($) {
// alert(2);
//}
//MM(jQuery)

// (function(str){alert(str)})("aaa");
////相当于:
//function OutPutFun(str) { alert(str); };
//OutPutFun("output");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: