BackboneJS:什么是选项 ||(选项 = {});在 Backbone 源代码中 [英] BackboneJS: What is options || (options = {}); in Backbone source code
问题描述
我正在浏览 BackboneJS 源代码,但无法弄清楚这一行是什么 options ||(options = {});
确实如此,因为没有对变量赋值.
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.
以下是来自 BackboneJS 的代码片段.
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);
};
推荐答案
但是有一个作业:
options || (options = {});
// ^^^^^^^^^^^^ Right there
所以如果 options
为假,options = { }
部分将被执行.由于 options
被指定为对象或 undefined
(即根本不传递),因此对象为真,undefined
为假,即如果指定了 options
,则表达式将不执行任何操作,如果未通过 options
,则设置 options = { }
.那个表达只是一种不同的写作方式:
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 = { };
请记住,表达式也可以作为 JavaScript 中的语句,因此您可以这样说:
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?';
在 JavaScript 中;这两个除了 options || 什么都不做(options = { })
有一个赋值作为副作用.大概是 options ||(options = { })
唤起了许多语言中可用的 options ||= { }
语法—但在 JavaScript 中不是 —所以这个符号很容易让 Backbone 作者阅读.
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.
这篇关于BackboneJS:什么是选项 ||(选项 = {});在 Backbone 源代码中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!