+ -
当前位置:首页 → 问答吧 → 为甚麽下面2段js执行结果不一样?

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

时间:2011-12-07

来源:互联网

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."。

作者: funnyone   发布时间: 2011-12-07

变量和赋值问题了。。你把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);

作者: zsx841021   发布时间: 2011-12-07

function(x) {
if (x == null) x = x;
参数x并不是外部的x,并且x=x赋值的x也不是外部的x而是参数x,所以第二个x为null,即使你判断了x==null的时候在x=x还是null

作者: chchawen   发布时间: 2011-12-07