3

Backbone.js的另一个函数

escape: function(attr) {
  var html;
  if (html = this._escapedAttributes[attr]) return html;
  ...

像上面那样做有什么好处?,而不是按照下面?

var html = this._escapedAttributes[attr];
if( html ) return html;
4

3 回答 3

2

这是优势还是令人困惑,很大程度上取决于您、您的团队和您的编码约定。

另一个可能非常有用的例子

function foo( arr, elem ) {
    while( elem = arr.shift() ) {
       console.log( elem * elem );
    }
}

你会在哪里使用它

foo([5,4,3,2,1]);

同样的事情也适用if statements。有时,在条件中为某个变量赋值是有意义或有帮助的,以便在案例中直接获得该访问权限。当然,对于一些不习惯它的人来说,这可能不方便,但同样,如果你的约定和你的团队就这样的事情达成一致,它可能会非常简洁。

其他语言默认提供此“功能”。例如,一个特殊的变量名,比如$_->只是自动引用你手上的东西。

于 2012-08-06T15:58:19.633 回答
1

没有优势*,这只是愚蠢。你知道,不可读是新的时尚。

* 除非您的编码约定是永远不要同时分配和声明变量。但我认为这在这里并不适用。

于 2012-08-06T15:50:09.807 回答
1

老实说,这样做并没有明显的优势。这会降低可读性并使代码更难维护。

如果你不得不为html变量重新赋值(就像它已经声明过的那样),它可能会稍微减少代码文件的大小,尽管这种减少完全可以忽略不计,除非出于某种未知和可怕的原因,它已经完成了数千次。例如,以下内容会更短:

function escape() {
    var html = "tree";
    // interact with html variable, and later on get to this:
    if (html = this._escapedAttributes[attr]) return html;
}

比这个:

function escape() {
    var html = "tree";
    // interact with html variable, and later on get to this:
    html = this._escapedAttributes[attr]
    if (html) return html;
}
于 2012-08-06T16:05:46.663 回答