views:

142

answers:

2

Can I have object with the same name as class in javascript?

+3  A: 

There are no classes per se in javascript, only methods that build objects.

To directly answer your question, yes and no. You can create a function that builds your object, but as soon as you have a variable of the same name, the function is destroyed.

there is no difference between

function bob() {
    //code goes here
    this.name = "bob";
}

and

var bob = function() {
    //code goes here
    this.name = "bob";
}


What would then happen if you declared a variable named bob like:

var bob = new bob();

In this case, the function bob would be called, the object created, and the function bob clobbered by the new variable bob.


If you want to create a singleton, then you might as well use a closure as follows:

var bob = new (function() {
    //code goes here
    this.name = "bob";
})();
Jonathan Fingland
so var bob = new bob(); is programmatically wrong ?
Rakesh
it's possible to do. the variable bob will now be an object that was created by the function bob. it's just that after that, the function bob will no longer be accessible (for invocation or instantiation)
Jonathan Fingland
@rakesh: just to add, whenever you are creating a variable name that is the exact same as your function name, you really need to ask yourself if it's necessary. It's quite common to name classes like SelectorPanel, and make instances named applicationSelectorPanel or layoutSelectorPanel (or just applicationPanel and layoutPanel). The class should be defining the kind (or class) of object to be created. The variable name should just be giving a meaningful label for what the object is.
Jonathan Fingland
@rakesh one more note (ran out of room on the last comment) you could even do something as simple as function Bob () { } and var bob= new Bob(); the two names would now be different due to a change in case of the first letter.
Jonathan Fingland
@Fingland, there's an error in the singleton example. It should either be var bob = new function(){ this.name = "Bob"; }; or var bob = {name : "Bob"}; -- the current version sets the "name" property of the global object, which you probably don't want.
gustafc
thanks gustafc. forgot the 'new'.
Jonathan Fingland
A: 

You can use the same name for class and variable, yes. But start the class with an uppercase letter and keep variable names lowercase. (Thus a class Bob and variable bob.)

Javascript is case sensitive so it knows the difference. For you, both would just read the same.

Workshop Alex