What does expression && expression syntax mean? [duplicate]

坚强是说给别人听的谎言 提交于 2021-02-08 12:36:13

问题


What does this line parent && (this.parent.next = this); mean? It just looks like its sitting there, doing nothing, not an if statement or a promise or anything. Is there a name for this style of coding?

    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;
}

Its in multiple places in this animation file I'm looking at. Here's another example.. (!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;

回答1:


It's shorthand for

if (parent) {
    this.parent.next = this
}



回答2:


if parent is false then not eject (this.parent.next = this), example:

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

Short-Circuit Evaluation:

As logical expressions are evaluated left to right, is named "short-circuit" evaluation,

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

it's possible to use for assignment of variables:

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


来源:https://stackoverflow.com/questions/29659521/what-does-expression-expression-syntax-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!