先来创建一个匿名函数对象:
/*** * 匿名函数 */ var callChangeBtn=new function(bugBtn){ this.chage=function(json){ bugBtn.removeAttribute("disable"); bugBtn.innerHTML="立即购买"; console.log(json); } }(event.target);
用new构造一个匿名函数对象,该对象有两个作用:
1、存了你要回调方法要使用的购买button element对象即你要传的数据。
2、为该对象定义回调方法的实现。
我们在ajax的回调方法要写成:
success:callChangeBtn.chage
参考资料1:
function ManageCallback(TargetTag) { this.Success=function(Json){ if(Json.Status==1){ //alert(Json.Message); TargetTag.innerText = Json.Message; //window.location.reload(); }else{ TargetTag.innerText = Json.ErrorMessage; //alert(Json.ErrorMessage); } } } function Manage(ID, Type, Action, NeedToConfirm, TargetTag) { if(NeedToConfirm?confirm("确定执行该操作?"):true){ TargetTag.innerText = "Loading"; var CallbackObj=new ManageCallback(TargetTag); $.ajax({ url:WebsitePath+"/manage", data:{ ID: ID, Type: Type, Action: Action }, cache: false, dataType: "json", type: "POST", success: CallbackObj.Success }); } }
参考资料2: javascript中匿名函数调用的多种方法
方式1,调用函数,得到返回值。强制运算符使函数调用执行
(function(x,y){ alert(x+y); return x+y; }(3,4));
方式2,调用函数,得到返回值。强制函数直接量执行再返回一个引用,引用再去调用执行
(function(x,y){ alert(x+y); return x+y; })(3,4);
这种方式也是很多库爱用的调用方式,如jQuery,Mootools。
方式3,使用void
void function(x) { x = x-1; alert(x); }(9);
方式4,使用-/+运算符
-function(x,y){ alert(x+y); return x+y; }(3,4); +function(x,y){ alert(x+y); return x+y; }(3,4); --function(x,y){ alert(x+y); return x+y; }(3,4); ++function(x,y){ alert(x+y); return x+y; }(3,4);
方式五
方式5,使用波浪符(~) ~function(x, y) { alert(x+y); return x+y; }(3, 4);
方式6,匿名函数执行放在中括号内
[function(){ console.log(this) // 浏览器得控制台输出window }(this)]
方式7,匿名函数前加typeof
typeof function(){ console.log(this) // 浏览器得控制台输出window }(this)
方式8,匿名函数前加delete
delete function(){ console.log(this) // 浏览器得控制台输出window }(this)
方式9,匿名函数前加void
void function(){ console.log(this) // 浏览器得控制台输出window }(this)
方式10,使用new方式,传参
new function(win){ console.log(win) // window }(this)
方式11,使用new,不传参
new function(){ console.log(this) // 这里的this就不是window了 }
方式12,逗号运算符
1, function(){ console.log(this) // window }();
方式13,按位异或运算符
1^function(){ console.log(this) // window }();
方式14,比较运算符
1>function(){ console.log(this) // window }();