BackboneJS: What is options || (options = {}); in

2019-02-19 09:50发布

问题:

I was going through BackboneJS source code and was unable to figure out what this line
options || (options = {}); does, since there is not assignment to a variable.

Following is the code snippet from BackboneJS.

  var Model = Backbone.Model = function(attributes, options) {
    var attrs = attributes || {};
    options || (options = {});
    this.cid = _.uniqueId('c');
    this.attributes = {};
    if (options.collection) this.collection = options.collection;
    if (options.parse) attrs = this.parse(attrs, options) || {};
    attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
    this.set(attrs, options);
    this.changed = {};
    this.initialize.apply(this, arguments);
  };

回答1:

But there is an assignment in there:

options || (options = {});
//          ^^^^^^^^^^^^ Right there

So if options is falsey, the options = { } part will be executed. Since options is specified to be an object or undefined (i.e. not passed at all), an object is truthy, and undefined is falsey, that expression will do nothing if options is specified and set options = { } if options is not passed. That expression is just a different way of writing:

if(!options)
    options = { };

Keep in mind that an expression also qualifies as a statement in JavaScript so you can say things like:

1 + 2;
'where is' + ' pancakes house?';

in JavaScript; those two do nothing at all but options || (options = { }) has an assignment as a side effect. Presumably options || (options = { }) is evocative of the options ||= { } syntax that is available in many languages — but not in JavaScript — so the notation is easy for the Backbone authors to read.