Skip to content Skip to sidebar Skip to footer

What Is The Difference Between Members On Prototype Object And On Constructor Function?

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 cl

Solution 1:

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.


Post a Comment for "What Is The Difference Between Members On Prototype Object And On Constructor Function?"