當我編寫代碼的時候,我嘗試將函數中的所有東西(方法,如果你喜歡的話)分開。功能X做東西X,Y做凝灰岩Y和不是就像方法X做東西X,Y & Z!這給了我更多的可重用代碼。我喜歡。 :)函數內部的調用函數
讓我們對這個代碼來看看:
var user = {
users: [],
userCount: 0,
addUser: function(user) {
(this.users).push(user);
},
incrementCount: function() {
++this.userCount;
}
}
var user = { // 2nd example.
users: [],
userCount: 0,
addUser: function(user) {
(this.users).push(user);
++this.userCount;
}
}
(這是在JavaScript中,但這裏的語言非必需)
在我看來,第二個例子會更容易和更安全的用於,可以說,API用戶。 很容易忘記撥打user.incrementCount()
。你怎麼看?第二個例子自動執行。
那麼如何找到平衡?有關在函數內部調用函數的最佳實踐?
感謝您閱讀本文。
編輯:
在此之前在我的腦海剛纔:
var user = {
users: [],
userCount: 0,
addUser: function(user) {
(this.users).push(user);
this.incrementCount();
},
incrementCount: function() {
++this.userCount;
}
}
所有API和'user'都只是一個例子。 – daGrevis
是的,我正在回答這個例子。 –