[英]Why and when we should use argument.length in ember.js
下面的代碼來自這里 。 但我不明白,為什么當作者使用fullName作為計算屬性時,他使用arguments.length
而不是value.length
檢查setter,這可能與分配給函數的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
if子句確保調用者已傳遞該值。
檢查arguments
的長度是正確的方法,即使您可能會遇到if (value)
或if (value !== undefined)
東西,或者在不太謹慎的代碼中遇到類似的東西。 檢查arguments.length
可區分僅使用一個參數(作為getter)調用的函數和使用兩個參數(作為setter),第二個參數undefined
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.