Capitalization convention for JavaScript objects - javascript

I know this question has no answer, but I'm curious to know what other people think.
In a language like Java, it's a convention to begin classes with capital letters, and objects with lowercase letters. But what about JavaScript, where everything is an object?
I've seen some people suggest capitalizing only objects that are treated as classes; i.e. function objects with a prototype, that are intended to be used with the new operator. Instances of those objects would be lowercased.
That sounds logical. But what do you do about "global objects", where there's only one instance? Most people seem to capitalize these (for example, Math or Ext.History). This intuitively feels right, but it's hard to justify it with a consistent rule.
And what about objects that are used as namespaces? These seem to be all over the map: YUI, Ext.util, jQuery, etc.
Please provide secular rationalizations for your heart-felt religious views.

You can follow this Google JavaScript Style Guide
In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.

As recommended by Douglas Crockford:
"Constructor functions that must be used with the new prefix should start with a capital letter. JavaScript issues neither a compile-time warning nor a run-time warning if a required new is omitted. Bad things can happen if new is missing, so the capitalization convention is an important defense."
https://www.crockford.com/code.html

The convention is that there is no convention. Do what you want, just be consistent. I suggest follow Java style and ignore whatever convention the library (dojo, Ext, YUI, $, etc) you happen to be using is following.

I agree with the capitalization of functions that define "classes" (air-quotes used) that in turn will be instanciated later using the new operator.
But that's it. Global objects are just global. Name them what you want.
All I would make sure is that they are unique and descriptive enough that they won't be overwritten accidentally by another developer at a later date.

Related

What is the primary purpose of function expression in Module Pattern

I know that Module Pattern is very useful and powerful in Javascript programming.
I recognized that pattern in Eric Miraglia's blog for the first time , but I am wondering one thing.
In other blogs and articles that explain Module Pattern, I notice that their sample codes are slightly different from Eric's article, that is, they use function expression with parenthesis rather than function statement, for example, the article from ben cherry is one of them.
Is there any specific reason to use function expression rather than function statement?
Please explain with easy way, I just entered into Javascript Programming world :)
The Miraglia pattern is the same, defining an anonymous function and executing it. The difference is that in order to use the features of the module, you must have a reference to an instance somewhere. Assigning the module to a global variable (YAHOO.*) is a way to retain the reference at a globally known spot, especially important for frameworks (like YUI).
Sometimes you don't need that reference. For example, if you are writing JavaScript for a web page, you often bind events to functions using selectors (ids / types, etc.) That really removes the need for any global reference to your module function.
Hope that make sense...

Javascript: $$ Global Variable Considered Evil?

I am writing a lot of Javascript code these days and I am making good use of JQuery. I am wondering if it is considered evil to create strange global variable names. I know that a lot of Javascript frameworks such as JQuery use the dollar character; $, but that greatly simplifies code as it can do so many things.
I am thinking of creating a $$ global variable in my code which would be defined as below:
function $$(tagName)
{
return $('<' + tagName + ' />');
}
The benefit of this is that my code has (1) abstracted out the logic of creating a new element, (2) made the code more concise, and lastly (3) I can almost create html elements within Javascript as concisely as html itself because JQuery has so many other selectors to chain off:
$$('div').attr( { id : 'myDiv', 'class' : 'MyDivClass' }).append(
$$('ul').append(
$$('li').text('first'),
$$('li').text('second'),
$$('li').text('third')
);
);
Do you believe the above approach of creating $$ is legitimate or would you regard it as a no-no?
This is of course an opinion, but if I was new to your application, I would have to go look up what that function does in order to understand the code. Also, the function is simple enough that other developers would likely not bother using it, so you'd end up with a mix of techniques which is confusing.. And really, is this so bad?
$('<div/>').attr( { id : 'myDiv', 'class' : 'MyDivClass' }).append(
$('<ul/>').append(
$('<li/>').text('first'),
$('<li/>').text('second'),
$('<li/>').text('third')
)
);
I prefer a clear, meaningful, self-documenting name over JQuery style $ any day of the year.
Also I find it confusing that the same name has different meanings depending on the context it is used in. Like $ in JQuery or this in javascript and will avoid using them as much as I can.
EDIT: In my opinion it should be up to the user to decide whether he wants to use a shorthand name for the framework he uses. It requires only one line of code:
var $ = jQuery;
When I look at pages with jQuery in it, all I see is a big mess flooded with dollar signs that do different things in different places. If the library had used meaningful names for the functions it offers it would be a lot easier to decipher other peoples code. Javascript is already difficult and unreadable as a language itself.
Personally I don't think it's adding that much functionality to account for the "namespace pollution", not to mention the possible confusion of people reading your code that aren't familiar with your method.
It's just saving a trivial couple of characters on each invocation of the method, so in that respect it can only be considered a form of syntactic sugar. And the cons outweigh the pros, in my opinion.
It would be good if you take a look at the construction of e.g. jQuery .
It does'nt work with several global variables/functions, there is only one global object required "jQuery" .
Everything else are properties of this one object, so they have minified naming-conflicts.
In the special case of $$ : maybe sometimes you need to work with prototypejs, but you cant, because prototypejs already uses $$.
So my suggestion: create one global object, your own "library" , give it a distinct name, and let your functions/variables be member of this object.
I don't think it's "evil" in general, but if you're going to pop something into the global namespace with a "distinguished" name it might be better if it were something a little more interesting. For your purposes, given your example code, the jQuery micro-template system would probably be a better approach anyway.

Why do I see JavaScript variables prefixed with $?

This is sort of a meta-question. Many snippets of JavaScript I've seen here on SO are named with a dollar sign prefix (for example, $id on the second line of the snippet shown in this question). I'm not referring to jQuery or other libraries. I am well aware that this is valid, but it seems awkward to do when not necessary. Why do people name their variables like this? Is it just familiarity with a server-side language like PHP carrying over into their JavaScript code?
I thought perhaps it was to identify a variable as being a jQuery object, for example when you save the result of a selection to a variable in order to eliminate duplicate selections later on, but I haven't seen any consistent convention.
Syntactically, the dollar sign itself means nothing -- to the interpreter, it's just another character, like _ or q. But a lot of people using jQuery and other similar frameworks will prefix variables that contain a jQuery object with a $ so that they are easily identified, and thus not mixed up with things like integers or strings. You could just as easily adopt the same convention by prefixing such variables with jq_ and it would have the same effect.
In effect, it is a crude sort of Hungarian notation.
I will sometimes prefix a variable name with $ to indicate that it is a jQuery-wrapped element (most often when I'm using $(this) in a function a lot, I will assign that to $this).
Part of where the lack of convention may come from is people copy-pasting code together that uses different conventions, thus producing inconsistent code.
Also, sometimes (rarely I hope) people who program in PHP a lot will put $'s at the beginning of their variable names out of habit.
I suspect the person in that example was just copying the jQuery pattern, or is used to PHP/Perl, without really understanding that it isn't necessary and has no special meaning.
However, I have seen [experienced] programmers use it for variable names that are reserved keywords, such as $class or $this. Or even for globals. It's really a personal preference more than anything, in that case.

What is the best-practice casing style for javascript? Why?

One aspect of javascript that it's hard to find information on is casing practices. By casing practices, I mean what casing style (ie. camel-case, pascal-case, etc) should be used for what elements (Constructors, private functions, public functions).
The only rule I've heard was from a Douglas Crockford lecture on YUI theater, stating that constructors should be the only functions that start with an uppercase letter.
Beyond that there doesn't seem to be many casing standards that people follow in javascript.
Does anyone know any casing best practices for javascript, and why it's reasonable to use them?
Also do you follow a casing style with your .js files?
I prefer PascalCase for constructors and camelCase for everything else. That's the style that JS standard library uses and well... every JS framework I've seen so far :)
And I use all_lowercase naming convention for all files served from web. There are some case-insensitive file systems out there.
The core language uses InitialCaps for constructors (e.g. Object, Date, Number, RegExp) and camelCase for methods and properties (e.g. something.toString(), quantity.valueOf(), regexp.ignoreCase). This convention is also followed in the DOM specifications and implementations (e.g. HTMLElement.setAttribute()). So it makes the most sense to adopt the same convention, or you finish up with a horrendous mishmash of styles like:
var number_of_fish_requested = document.getElementById("fish").value;
var fish_count = parseInt(number_of_fish_requested, 10);
which just becomes utterly confusing, not only to type but, much more importantly, to read.
(You spend more time reading code, trying to debug or modify it, than you ever do writing it in the first place.)
What I have seen so far is a very large diversity of casing standards.
As far as I'm concerned, I use C# styling for writing my JavaScript code. I use classes a lot (well functions as classes, and usually don't have independent functions.)
So, I use PascalCase for class names, public methods, properties and all global variables and camelCase for arguments, local variables and private functions. This somehow reflects my common environment, helping to distinguish the variable scopes.
I also tend to keep my class functions in a separate file with the same name as my ClassName (ClassName.js, ClassName.min.js).
This was about my approach.
I also noticed that Java programmers, follow the Java rules (and the writing style resembles the Java language.) Ruby on Rails programmers follow their own naming standards such as underscore_separated_var_name.
Further, as you mentioned, there is a tendency to use pascalCase a lot in naming in very popular frameworks whose authors come from different communities like Linux/Open source community and Microsoft developers (jQuery, knockout.js, JSJaC, etc.)
I should note that none of these methods are wrong or right, when it comes to JS. The primary purpose of your naming conventions and file structuring is the readability. If you are consistent then you in future and your fellow developers will quickly understand and get on with your code.
I prefer camelCase for everything except for constructors. The reason (and I believe this is why Mr. Crockford suggested this as well) is because in other languages, such as Java, the convention is capitalize your classes, which is what constructors are used for.
That is my $0.02.
All lower case with underscore separators is the easiest to read; it follows natural language. "Best" will get you in to a holy war; the reality is case doesn't matter as much as other design issues but it's an easy topic to polarize.
ALongButNotReallyReadableIdentifier
an_even_longer_but_completely_readable_identifier
The accepted answer is true but there are some exceptions.
In window.JSON and window.XMLHttpRequest the term is capitalized.
Also most people use PascalCase for enum type objects in Javascript and capitalized values within. Sometimes namespaces are done in PascalCase also.
example:
MyCompany.Web.UI.MyComponent.ThemeOption = { BLACK: 0, SILVER: 1, BLUE: 2}

What lessons can be learned from the prototype model in javascript?

The question is from a language design perspective.
I should explain a little about the situation. I am working on a javascript variant which does not support prototypes, however it is overdue a decent type system (most importantly support for instanceof). The ecmascript spec is not important, so i have the freedom to implement something different and better suited.
In the variant:-
You do not declare constructors with function foo(), rather constructors are declared in template files, which means constructors exist in a namespace (detirmined by the path of the file)
Currently all inheritance of behaviour is done by applying templates which means all shared functions are copied to each individual object (there are no prototypes afterall).
Never having been a web developer, this puts me in the slightly bizarre position of never having used prototypes in anger. Though this hasn't stopped me having opinions on them.
My principal issues with the prototype model as i understand it are
unnecessary littering of object namespace, obj.prototype, obj.constructor (is this an immature objection, trying to retain ability to treat objects as maps, which perhaps they are not?)
ability to change shared behaviour at runtime seems unnecessary, when directly using an extra level of indirection would be more straight forward obj.shared.foo(). Particularly it is quite a big implementation headache
people do not seem to understand prototypes very well generally e.g. the distinction between a prototype and a constructor.
So to get around these my idea is to have a special operator constructorsof. Basically the principal is that each object has a list of constructors, which occasionally you will want access to.
var x = new com.acme.X();
com.acme.Y(x,[]); // apply y
(constructorsof x) // [com.acme.Y,com.acme.X,Object];
x instanceof com.acme.X; // true
x instanceof com.acme.Y; // true
All feedback appreciated, I appreciate it maybe difficult to appreciate my POV as there is a lot i am trying to convey, but its an important decision and an expert opinion could be invaluable.
anything that can improve my understanding of the prototype model, the good and the bad.
thoughts on my proposal
thanks,
mike
edit: proposal hopefully makes sense now.
Steve Yegge has written a good technical article about the prototype model.
I don't think your issues with the prototype model are valid:
unnecessary littering of object namespace, obj.prototype, obj.constructor
prototype is a property of the contructor function, not the object instance. Also, the problem isn't as bad as it sounds because of the [[DontEnum]] attribute, which unfortunately can't be set programatically. Some of the perceived problems would go away if you could.
is this an immature objection, trying to retain ability to treat objects as maps, which perhaps they are not?
There's no problem with using objects as maps as long as the keys are strings and you check hasOwnProperty().
ability to change shared behaviour at runtime seems unnecessary, when directly using an extra level of indirection would be more straight forward obj.shared.foo(). Particularly it is quite a big implementation headache
I don't see where the big implementation headache in implementning the prototype chain lies. In fact, I consider prototypical inheritance conceptually simpler than class-based inheritance, which doesn't offer any benefits in languages with late-binding.
people do not seem to understand prototypes very well generally e.g. the distinction between a prototype and a constructor.
People who only know class-based oo languages like Java and C++ don't understand JavaScript's inheritance system, news at 11.
In addition to MarkusQ's suggestions, you might also want to check out Io.
It might just be easier to try a few things with practical code. Create the language with one simple syntax, whatever that is, and implement something in that language. Then, after a few iterations of refactoring, identify the features that are obstacles to reading and writing the code. Add, alter or remove what you need to improve the language. Do this a few times.
Be sure your test-code really exercises all parts of your language, even with some bits that really try to break it. Try to do everything wrong in your tests (as well as everything right)
Reading up on "self", the language that pioneered the prototype model, will probably help you more than just thinking of it in terms of javascript (especially since you seem to associate that, as many do, with "web programming"). A few links to get you started:
http://selflanguage.org/
http://www.self-support.com/
Remember, those who fail to learn history are doomed to reimplement it.

Categories