Can I have object with the same name as class in javascript?
5 Answers
There are no classes per se in javascript, only methods that build objects.
UPDATE: ES6, also known as ECMAScript2015, introduced classes.
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";
})();
4 Comments
For this case, you should make your global function and other options of your specific function name like below:
var write = function(text) { console.log(text); }
write.hi = ()=>console.log("hi");
write.bye = ()=>console.log("bye");
write.word = (text)=>console.log(text);
write.feature = "Its a feature";
//...
write("baby");//'hello' printed
write.hi();//'hi' printed
write.bye();//'bye' printed
//...
Enjoy...
Comments
I'm answering assuming keeping in mind the best practises. Usually objects in JavaScript are defined as const. In such cases, having the same object name as class name will cause an error.
If the object is not defined as const, the new object will overwrite the class.
Either ways the outcome of attempting something like this is not good, so one should refrain from this practise and try keeping different name for classes and objects.
But if there is a special situation, you can try changing the Class name using TitleCasing and object name with camelCasing or any other variations.