javascript小陷阱
//有点意思
case 1:
functiona(x) {
console.log(x);
function b() {
var x= x || 8;
console.log(x);
}
b()
}
a(3);//猜猜?
case 2:
function a(x) {
console.log(x);
function b() {
var x;
x= x || 8;
console.log(x);
}
b()
}
a(3); //猜猜?
结果是一样的,都是3,8;为什么不是3,3呢?原因也很简单,函数b中的var x在作怪,使得在b中x的值首先变成了undefined,
var x=x||8;与var x;x=x||8 是等价的,前面那种形式实际上会先被js引擎转换成后者,
自然x=undefined||8会得到x=8。
之所以提到这个小问题,是因为在一个项目中不小心写了这样的代码:
var cache={
readServer:function (callback) {
var paramsObj = {
lemmaId:commonSubmitData.lemmaId,
versionId:commonSubmitData.versionId,
subLemmaId:dynamicData.activeSubLemmaId,
subVersionId:dynamicData.activeSubVersionId,
type:1
};
var paramsStr = baidu.url.jsonToQuery(paramsObj),
self = this;
initData.communicating = true;
ajax.post(initData.doubtShowUrl, paramsStr, function (xhr, msg) {
initData.firstClick = false;
initData.communicating = false;
if (!self.doubtDataCache[dynamicData.activeSubLemmaId]) {
self.doubtDataCache[dynamicData.activeSubLemmaId] = json.parse(msg);
}
//下面两行是错误的
var callback=callback||function(){};
callback.call(self, self.doubtDataCache[dynamicData.activeSubLemmaId]);
/***这里是正确的
if(lang.isFunction(callback)){
callback.call(self, self.doubtDataCache[dynamicData.activeSubLemmaId]);
}
*/
//console.log(callback);
});
}
readServer:function (callback) {
var paramsObj = {
lemmaId:commonSubmitData.lemmaId,
versionId:commonSubmitData.versionId,
subLemmaId:dynamicData.activeSubLemmaId,
subVersionId:dynamicData.activeSubVersionId,
type:1
};
var paramsStr = baidu.url.jsonToQuery(paramsObj),
self = this;
initData.communicating = true;
ajax.post(initData.doubtShowUrl, paramsStr, function (xhr, msg) {
initData.firstClick = false;
initData.communicating = false;
if (!self.doubtDataCache[dynamicData.activeSubLemmaId]) {
self.doubtDataCache[dynamicData.activeSubLemmaId] = json.parse(msg);
}
//下面两行是错误的
var callback=callback||function(){};
callback.call(self, self.doubtDataCache[dynamicData.activeSubLemmaId]);
/***这里是正确的
if(lang.isFunction(callback)){
callback.call(self, self.doubtDataCache[dynamicData.activeSubLemmaId]);
}
*/
//console.log(callback);
});
}
}