表达式&&表达式语法是什么意思?

Fem*_*ond 10 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;
}
Run Code Online (Sandbox Code Playgroud)

它在我正在看的动画文件的多个地方.这是另一个例子..(!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;
Run Code Online (Sandbox Code Playgroud)

tym*_*eJV 16

这是简写

if (parent) {
    this.parent.next = this
}
Run Code Online (Sandbox Code Playgroud)

  • 没有优势.当其他人维护/阅读您的代码时,它会更难以遵循. (18认同)
  • 不是很短 (4认同)
  • 这是一个非常便于维护的捷径. (2认同)
  • @Leushenko`if(parent)this.parent.next = this;`.那里:现在它是一条线,并且比那个奇怪的布尔表达式在视觉上更复杂.由于赋值基本上是一种陈述(它会产生副作用),因此在大多数情况下尝试将其变成表达式是一个坏主意,所以最后一点是没有意义的. (2认同)

Jos*_* M. 7

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

parent = false;
parent && alert("not run");
Run Code Online (Sandbox Code Playgroud)

短路评估:

逻辑表达式从左到右进行评估,被称为"短路"评估,

variable && (anything); // anything is evaluated if variable = true.
variable || (anything); // anything is evaluated if variable = false
Run Code Online (Sandbox Code Playgroud)

它可以用于变量的赋值:

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