0

My question is not about the difference between object's members and prototype members. I understand that. I think it is similar like C# object members and static members on the class.

My question is about difference between members on constructor function and on prototype object. Comparing to C# they both are "static". So what is the difference? I only observed, that prototype members can be called the same way on instances directly, or on Constructor.prototype. The constructor function members can be called only on constructor function. When to use which approach?

To illustrate this, imagine I need count of Persons.


Example using constructor function members:

function Person () {
    Person.countOfCreatedPersons = (Person.countOfCreatedPersons || 0) + 1;
}

Person.Count = function () {
    return Person.countOfCreatedPersons;
}

var p = new Person();
alert(Person.Count());

Example using prototype members:

function Person () {
    Person.prototype.countOfCreatedPersons = (Person.prototype.countOfCreatedPersons || 0) + 1;
}

Person.prototype = {
    Count: function () {
        return this.countOfCreatedPersons;
    }
}

var p = new Person();
alert(Person.prototype.Count()); // or p.Count()
Marťas
  • 982
  • 6
  • 17
  • possible duplicate of [class/static method in javascript?](http://stackoverflow.com/questions/7694501/class-static-method-in-javascript) – zzzzBov Mar 13 '14 at 16:36

1 Answers1

0

When you add a property to the prototype of an object, every object that inherits from that prototype has the property:

function Ob(){};

Ob.prototype.initialised = true;

var ob1 = new Ob();
alert(ob1.initialised);  //true!
alert(Ob.initialised); //undefined;

If you add it to the constructor, is like a static property. Instances won't have acces to them.

function Ob2(){};

Ob2.initialised = true;
var ob2 = new Ob2();
alert(ob2.initialised); //undefined
alert(Ob2.initialised); //true

Besides, if you add a method to the prototype, the this variable inside the method will point to your object (the instance of the class you've created with new). This is not true for class methods:

function Obj() {
    this.value = 1;
}

Obj.prototype.getValue = function() { 
    return this.value; 
};

Obj.getValue = function() {
    return this.value;
};

var ob3 = new Obj();
alert(ob3.getValue()); //'1'!
alert(Obj.getValue()); //undefined!

Hope this explains.

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42