什么是表达和&&表达式语法是什

时间:2015-04-15 19:49:17

标签: javascript short-circuiting

这一行parent && (this.parent.next = this);是什么意思? 它只是看起来像坐在那里,什么也不做,不是if声明或承诺或任何东西。这种编码风格有名称吗?

    var Particle = function(i, parent)
{
    this.next = null;
    this.parent = parent;
    parent && (this.parent.next = this);
    this.img = new Image();
    this.img.src = "http://www.dhteumeuleu.com/images/cloud_01.gif";
    this.speed = speed / this.radius;
}

它在这个动画文件中的多个位置我正在看。这是另一个例子.. (!touch && document.setCapture) && document.setCapture();

this.down = function(e, touch)
{
    e.preventDefault();
    var pointer = touch ? e.touches[0] : e;
    (!touch && document.setCapture) && document.setCapture();
    this.pointer.x = pointer.clientX;
    this.pointer.y = pointer.clientY;
    this.pointer.isDown = true;

2 个答案:

答案 0 :(得分:16)

这是

的简写
if (parent) {
    this.parent.next = this
}

答案 1 :(得分:7)

如果parent为false则不弹出(this.parent.next = this),例如:

parent = false;
parent && alert("not run");

短路评估:

逻辑表达式从左到右进行评估,命名为"短路"评价,

variable && (anything); // anything is evaluated if variable = true.
variable || (anything); // anything is evaluated if variable = false

可以用来分配变量:

var name = nametemp || "John Doe"; // assignment defaults if nametemp is false
var name = isValid(person) && person.getName(); //assignement if person is valid