1

Would the following:

function ClassName() {}

be equal to:

var ClassName = function(){}

?

I'm trying to do the following:

MODULE = (function(x) {

    x.ClassName = function(){}
    // add some functions to ClassName class...
    return x
})(MODULE);

Given what I've read elsewhere on how to create a class, I'm not sure if this is correct?

UPDATE: Ok you can just use object literals as well e.g.

var ClassName = {}
  • possible duplicate of [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Wiktor Zychla Jan 09 '15 at 22:25
  • The answer in the link you provided would not have helped me. However, should you feel I am wrong, then you are more than welcome to delete this post. –  Jan 09 '15 at 22:29
  • There are no classes, only Objects. – Evan Davis Jan 09 '15 at 23:47

2 Answers2

0

Yes, this is valid:

var ClassName = function(){}

You can give it a try:

var ClassName = function(){}
var a = new ClassName();
document.writeln(typeof a); //object
document.writeln(a instanceof ClassName); //true
Theraot
  • 31,890
  • 5
  • 57
  • 86
  • I don't know much about this language but im LOVING it thus far. Thank you Theraot. –  Jan 09 '15 at 22:30
0

function className() {} and var className = function(){} represent the same thing. See the examples below:

function Person(name, age){

        this.name = name;
        this.age = age;
     }

    Person.prototype.howOld =function(){
        console.log(this.name + " is " + this.age + " years old")
    }
    var person1 = new Person("John", 29);
    person1.howOld(); //John is 29 years old

The above would give you the same output as the below:

var Person = function(name, age){
    this.name = name;
    this.age = age;
 }

Person.prototype.howOld =function(){
    console.log(this.name + " is " + this.age + " years old")
}
var person1 = new Person("John", 29); 
person1.howOld(); //John is 29 years old

UPDATE: If you look at the two from a purely functional point of view, you might want to consider something called hoisting. The above is just to show their similarity from a class/object point of view.

user3681587
  • 566
  • 5
  • 12
  • The two styles differ in timing. The `function Person() {}` style is hoisted to the top of the current scope so it will be available for us ANYWHERE in the scope. The `var Person = function() {}` style is only valid AFTER the definition in the current scope. – jfriend00 Jan 09 '15 at 23:28
  • Yes, but, I was just interested in stating their similarity when it comes to inheritance. But hoisting can be a factor depending on what you want to accomplish. – user3681587 Jan 09 '15 at 23:40
  • You said "represents the same thing" which is 99% true, but not 100% true (because of the hoisting difference). – jfriend00 Jan 09 '15 at 23:42