简体   繁体   中英

Naming convention to distinguish between module / instance / method variables in node JS

Suppose I have some code like this :

var moduleVar = "I belong to this module, you could also call me a static var";

var ClassName = function() {
    var instanceVar = "I belong to this instance";

    function someFunction(functionVar) {
        var anotherFunctionVar = "I belong to this function";
        return 1;
    }
}

module.exports = ClassName;

I've looked around for naming conventions for node, but I haven't found anything that even deals with this issue. I like prefixing instance variables with underscore (eg "_instanceVar"), but I'm still stuck on a difference between the function and module variables.

Is there a naming convention out there that differentiates these ?

This is subjective, by team/developer. I have generally seen "classes" defined with upper case, and basically everything else is lower case. Methods, instance vars, function params . . . just everything!

Basic web search led me to this: http://www.j-io.org/Javascript-Naming_Conventions/#naming-conventions

The underscore is typically reserved for "private" instance variables. Really, you don't see many "my*" or "m_" stuff in javascript - and I think that's just the lack of classes and Object Oriented concepts that don't carry over as well.

Which all makes things difficult sometimes, as you don't know if your variable is a primitive, an object, an array or a function! Since things are not strong typed, I think that opens the door to Hungarian Notation more than camelCase, but you don't see that very often either (so we don't do it : )

Last thing - some things can be checked and constrained by JSHint . Use that, or jslint , so you don't forget your convention, and write generally conforming code. Definitely enforces how you code (I'm still switching from double quotes to single quotes : )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM