日期:2014-05-16  浏览次数:20346 次

为甚麽下面2段js执行结果不一样?
JScript code

(function() {
var showAnswer, x;
x = true;
showAnswer = function() {
x = x;
return alert(x ? 'It works!' : 'Nope.');
};
$(function() {
return $('#click').click(function() {
return showAnswer();
});
});
}).call(this);




JScript code

(function() {
var showAnswer, x;
var _this = this;
x = true;
showAnswer = function(x) {
if (x == null) x = x;
return alert(x ? 'It works!' : 'Nope.');
};
$(function() {
return $('#click').click(function() {
return showAnswer();
});
});
}).call(this);



<button id="click">click me</button>
HTML code





第一个结果 是"It works!",第二个"Nope."。

------解决方案--------------------
变量和赋值问题了。。你把function(x)这里面的x换成别的变量你就会发现其实是一样的
(function () {
var showAnswer, x;
var _this = this;
x = true;
showAnswer = function (a) {
if (a == null) {
a = x;
return alert(a ? 'It works!' : 'Nope.');
}
};
$(function () {
return $('#click').click(function () {
return showAnswer();
});
});
}).call(this);
------解决方案--------------------
function(x) {
if (x == null) x = x;
参数x并不是外部的x,并且x=x赋值的x也不是外部的x而是参数x,所以第二个x为null,即使你判断了x==null的时候在x=x还是null