【发布时间】:2012-01-12 20:05:31
【问题描述】:
当我编写代码时,我会尝试将所有内容划分为函数(方法,如果你喜欢的话)。函数 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;
}
}
【问题讨论】:
标签: javascript oop coding-style code-reuse