[英]Mocking private scope identifier with eval
While programming a server application for multiplayer games, I got an idea for cleaning up my code a bit. 在编写用于多人游戏的服务器应用程序时,我想到了一些清理代码的想法。
I'm heavily using the Module Pattern
for my application and use a convention for calling exposed functions public[Function name]
and privates private[Function name]
. 我在我的应用程序中大量使用
Module Pattern
,并使用约定来调用公开的函数public[Function name]
和privates private[Function name]
。 The public
prefix helps in the return assignment: public
前缀有助于返回分配:
return {
get : publicGet
}
But the private identifier names are just for show and make calling them a bit cumbersome. 但是专用标识符名称仅用于显示,因此调用它们有些麻烦。 However, completely removing the
private
prefix makes the code a bit less readable. 但是,完全删除
private
前缀会使代码的可读性降低。 So I thought of using the reserved private
keyword as you would in, for example, Java. 因此,我想到了像在Java中那样使用保留的
private
关键字。
For doing this I thought I could use eval
like this: 为此,我认为我可以这样使用
eval
:
var private = eval('') // Just an empty assignment so it does nothing.
So I can write my private function like this: 所以我可以这样写我的私有函数:
private function initiateGameMatchmaker(game) {
// Code...
}
Instead of: 代替:
function privateInitiateGameMatchmaker(game) {
// Code...
}
Would this be acceptable or do you regard this as a filthy hack and thus as a definite no-no? 这是可以接受的,还是您认为这是肮脏的俩,因此是绝对不可以吗?
Acceptable or not, it won't work. 可接受与否,它将不起作用。
private
will be undefined
, and private function foo(){}
will throw a SyntaxError: Unexpected token function
. private
将是undefined
,而private function foo(){}
将抛出SyntaxError: Unexpected token function
。
Don't try to mold JavaScript into the conventions of a language it's not. 不要试图将JavaScript塑造成不是它的语言习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.