单行 || Javascript 中的字符?

Single line of || character in Javascript?

我正在尝试理解 Fabric.js javascript 库的 _drawControl 函数,但无法理解其中的 2 行,因为它们看起来不像函数,不是条件if,那么这里的目的是什么?

第 1 行:

isVML() || this.transparentCorners || ctx.clearRect(left, top, size, size);

第 2 行:

ctx[methodName + 'Rect'](left, top, size, size);

全功能:

_drawControl: function(control, ctx, methodName, left, top) {
  if (!this.isControlVisible(control)) {
    return;
  }
  var size = this.cornerSize, stroke = !this.transparentCorners && this.cornerStrokeColor;
  switch (this.cornerStyle) {
    case 'circle':
      ctx.beginPath();
      ctx.arc(left + size / 2, top + size / 2, size / 2, 0, 2 * Math.PI, false);
      ctx[methodName]();
      if (stroke) {
        ctx.stroke();
      }
      break;
    default:
      isVML() || this.transparentCorners || ctx.clearRect(left, top, size, size);
      ctx[methodName + 'Rect'](left, top, size, size);
      if (stroke) {
        ctx.strokeRect(left, top, size, size);
      }
  }
}

|| 运算符在这种情况下用于 short-circuit evaluation。它从执行 isVML() 开始,如果 return 是一个假值,它将继续执行下一条语句 (this.transparentCorners) 并检查相同的语句。当达到真实值时,该值将被 returned。在这种情况下,不使用 return 值。

很简单。第一个短路并采用第一个真参数:

let foo = false || "foo" || "never reached";
console.log(foo); // foo

let bar = "bar" || "never reached" || false;
console.log(bar); // bar

第二个通过括号表示法调用对象的方法(使用 4 个参数)- 它用于动态调用方法:

function Foo() {
  
}

Foo.prototype.bar = function() {
    console.log('bar');
  }


let foo = new Foo();
let variable = 'bar';
foo[variable]();

// same as

foo.bar();