var testFunc = function(){
if(typeof XMLHttpRequest != 'undefined'){
testFunc = function(){
alert('1');
}
} else if(typeof ActiveXobject != 'undefined') {
testFunc = function(){
alert('2');
}
} else {
testFunc = function(){
alert('3');
}
}
}
此函数在每次调用的时候都会执行判断,我们希望这个判断只执行一次,有两种方式可以实现。
第一种是在函数被调用时候处理,代码如下:
var testFunc = function(){
if(typeof XMLHttpRequest != 'undefined'){
testFunc = function(){
alert('1');
}
} else if(typeof ActiveXobject != 'undefined') {
testFunc = function(){
alert('2');
}
} else {
testFunc = function(){
alert('3');
}
}
}var testFunc = (function(){
if(typeof XMLHttpRequest != 'undefined'){
return function(){
alert('1');
}
} else if(typeof ActiveXobject != 'undefined') {
return function(){
alert('2');
}
} else {
return function(){
alert('3');
}
}
});原文:http://blog.csdn.net/yuyang2013/article/details/42494839