BackboneJS:什么是期权|| (选项= {});在骨干源$ C ​​$ C [英] BackboneJS: What is options || (options = {}); in Backbone source code

查看:82
本文介绍了BackboneJS:什么是期权|| (选项= {});在骨干源$ C ​​$ C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在经历BackboneJS源$ C ​​$ c和无法弄清楚这行
选项|| (选项= {}); 确实,因为没有分配给一个变​​量

以下是从BackboneJS的code片段。

  VAR模型= Backbone.Model =功能(属性,选项){
    VAR ATTRS =属性|| {};
    选择|| (选项= {});
    this.cid = _.uniqueId('C');
    this.attributes = {};
    如果(options.collection)this.collection = options.collection;
    如果(options.parse)ATTRS = this.parse(ATTRS,期权)|| {};
    ATTRS = _.defaults({},ATTRS,_.result(这一点,'缺省'));
    this.set(ATTRS,期权);
    this.changed = {};
    this.initialize.apply(这一点,参数);
  };


解决方案

的分配在那里:

 选项|| (选项= {});
// ^^^^^^^^^^^^就在那里

所以,如果选项是falsey,在选项= {} 部分将被执行。由于选项被指定为一个对象或未定义(即所有未通过),对象是truthy和未定义是falsey,即前pression会做什么,如果选项指定并设置选项= {} 如果选项未通过。这当然pression是写作只是一种不同的方式:

 如果(!期权)
    选项​​= {};

请记住,一个前pression也有资格作为一个JavaScript语句,这样你可以说这样的话:

  1 + 2;
哪里是'+'煎饼的房子吗?;

在JavaScript中;这两个什么也不做,但选项|| (选项= {})有赋值的副作用。 presumably 选项|| (选项= {})是令人回味的选项|| = {} 语法,在许多语言&MDASH可用;但不可以在JavaScript中—这样的符号容易使骨干作者阅读。

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

解决方案

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.

这篇关于BackboneJS:什么是期权|| (选项= {});在骨干源$ C ​​$ C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆