0

下面的代码取自这里。但我不明白,为什么在作者使用 fullName 作为计算属性的时候,他用arguments.length而不是检查 setter value.length,这可能与value分配给函数的变量有关。我想知道有什么区别以及为什么他在这种情况下使用 arguments.length

App.Person = Ember.Object.extend({
  firstName: null,
  lastName: null,

  fullName: function(key, value) {
    // setter
    if (arguments.length > 1) {
      var nameParts = value.split(/\s+/);
      this.set('firstName', nameParts[0]);
      this.set('lastName',  nameParts[1]);
    }

    // getter
    return this.get('firstName') + ' ' + this.get('lastName');
  }.property('firstName', 'lastName')
});


var captainAmerica = App.Person.create();
captainAmerica.set('fullName', "William Burnside");
captainAmerica.get('firstName'); // William
captainAmerica.get('lastName'); // Burnside
4

1 回答 1

2

if 子句确保调用者已经传递了值。

检查的长度arguments是正确的方法,即使您可能会在不太仔细的代码中遇到类似if (value)或类似的事情。if (value !== undefined)检查arguments.length区分仅使用一个参数(作为 getter)调用的函数和使用两个参数(作为 setter)调用的函数,第二个参数是undefined.

于 2013-09-30T16:50:51.570 回答