1

Possible Duplicate:
&& operator in Javascript

In the sample code of the ExtJS web desktop demo there is the following call:

this.setActiveButton(activeWindow && activeWindow.taskButton);

to method:

setActiveButton: function(btn) {
    if (btn) {
        btn.toggle(true);
    } else {
        this.items.each(function (item) {
            if (item.isButton) {
                item.toggle(false);
            }
        });
    }
}

What is the purpose of the && in the function call?

4

2 回答 2

3

It's to make sure that, before trying to find a property on an object referenced by the variable "activeWindow", the variable actually does reference something. If it's null (or a few other things; we'll assume the code knows that it's either an object reference or null), that would cause an exception. This way, the function is passed either the button reference (whatever that is), or null.

To put it another way, it's the same as this:

this.setActiveButton(activeWindow != null ? activeWindow.taskButton : null)

The && operator in JavaScript is kind-of special compared to the && in C or Java or other languages like that. In JavaScript, the left side is evaluated first. If that value is "falsy" (null, undefined, false, zero, or an empty string), then that's the value of the expression. Otherwise, the value of the expression is the value of the right-hand side.

于 2012-07-02T16:28:04.587 回答
1

See Short-circuit evaluation for additional information regarding this method.

The short-circuit expression x Sand y (using Sand to denote the short-circuit variety) is equivalent to the conditional expression if x then y else false; the expression x Sor y is equivalent to if x then true else y.

于 2012-07-02T16:29:16.990 回答