日期:2014-05-18  浏览次数:20647 次

请教js 赋值 带|| 的问题
function test(p)
{
  this.a = p || false;
}
请教下 this.a = p || false; 怎么理解


------解决方案--------------------
如果 p 是 null 或者是采用 test() 方式直接调用的话,JavaScript 就隐含地认为 p 的值是 false,这时就会采用 || 右边的值。

这种方式可以给一些参数设定默认值,这在 JavaScript 程序中是一种很常用的做法。
------解决方案--------------------
在浏览器中运行一下这个 HTML,看看 alert 会出现什么就能明白了

HTML code
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>试试</title>
</head>

<script type="text/javascript">
var Test = function(p1, p2, p3) {
  this.p1 = p1 || 'p1',
  this.p2 = p2 || 'p2',
  this.p3 = p3 || 'p3'
}

Test.prototype = {
  getP1 : function() {
    return this.p1;
  },

  getP2 : function() {
    return this.p2;
  },

  getP3 : function() {
    return this.p3;
  }
}

window.onload = function() {
  var t0 = new Test();
  alert('p1=' + t0.getP1() + ', p2=' + t0.getP2() + ', p3=' + t0.getP3());

  var t1 = new Test('1');
  alert('p1=' + t1.getP1() + ', p2=' + t1.getP2() + ', p3=' + t1.getP3());
  
  var t2 = new Test('1', '2');
  alert('p1=' + t2.getP1() + ', p2=' + t2.getP2() + ', p3=' + t2.getP3());
  
  var t3 = new Test('1', '2', '3');
  alert('p1=' + t3.getP1() + ', p2=' + t3.getP2() + ', p3=' + t3.getP3());
}
</script>

<body>

</body>
</html>