当我编写代码时,我会尝试将所有内容划分为函数(方法,如果您愿意)。函数 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;
}
}
最佳答案
在 JS 中有点不同,因为在使用对象字面量表示法时没有办法使函数真正私有(private),但是...
一切都与您希望对象向其消费者公开的 API 有关。您是否希望 API 的消费者能够独立于添加用户来增加计数?如果是这样:
{ addUser: /* snip */, incrementCount: /* snip */ }
否则:
{ addUser: /* snip */, _incrementCount: /* snip */ }
// or just
{ addUser: /* snip */ }
在这种特殊情况下,我强烈建议不要存储任何单独的计数,因为 users
数组已经为您完成了。
var user = {
_users: [],
addUser: function(user) {
this._users.push(user);
},
getUserCount: function () {
return this._users.length;
}
// and if you need to expose the users array directly,
, getUsers: function () {
return this._users;
}
}
关于javascript - 在函数内部调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8379279/