I've really been getting into nodejs lately, ive found the way javascript does objects a little weird compared to other languages tho, the so called prototype based way rather than actually using classes.

Here is some code which should explain how some of it is done and how it would relate to a standard class system with public/private and friends.

//Constructor for Container    
Container = function() {
    //Private variable
    var v1 = 10; 

    //Public variable 
    this.v2 = 10; 

    //Private method 
    //Only assessable within other methods declared here.
    //Can access v1 and v2
    //Kind of shorthand to var f1 = function f1() { } (See bellow) 
    function f1() {

    }

    //Privileged method
    //Externally callable
    //This can access v1 and v2..
    this.f2 = function() {

    }
}

//Public method, 
//This can access v2 but not v1
Container.prototype.f3 = function () {

}

//Also a public var
//Same as this.variable = in constructor
Container.prototype.v3 = 10;

Now what exactly is up with

function foo() { }; vs 
var foo = function() { }; vs
var foo = function foo() {}; 

The first is a declaration while the other two are expressions/assignments, they have a few interesting differences

  • The declaration can be called anywhere as it is evaluated before any code is executed.
  • The expression can only be ran by code used after the variable has been assigned.

The third case is equivalent to the second case, having the name can come in useful when debugging ie console.log(foo.name) or when doing recursive calls where you have to reference the function inside it self.

Back