woensdag 14 juli 2010

Da Prototype

Hi,

as i've promised, i would like to mention few things about the usage of the prototype in object oriented javascript. prototype is a reserved keyword in javascript. Prototype of a class is nothing but a native javascript object, surrounded with bracelets { and contains key value pairs that are seperated with a double point {key:value}. You can access these properties everywhere. Not a big deal isn't it? Let's see some code to understand;

function MyClass(){
this.firstVal = 2;
this.allVals = function(){
alert(this.firstVal+this.secondVal);
}
}

If we run this code as it is, we will get some errors because the secondVal is not defined. You can test like this;

var x = new MyClass();
//we call the function by using paranthesis otherwise it will return the function as string.
x.allVals();
alert(typeof(x.secondVal));

and the result will be "undefined". You can ofcourse add this undefined property manually;

x.secondVal = 2;
x.allVals();

this is going to alert "4" but if you add the property to the instance, it won't be reflected to the other instances. Now notice how i define the properties in the prototype and use them in the constructor;

function Otherclass(){
this.allVals = function(){
//i use this keyword to access the properties in the prototype
alert(this.firstVal+this.secondVal);
}
}

Otherclass.prototype = {
firstVal: 2,
secondVal: 2
}

One important thing, if you add a property to the prototype by using the instance, all instances of the same class will have the same property;

var a = new Otherclass();
var b = new Otherclass();

a.prototype.customVal = "Hello world";
alert(b.customVal);

Because you've added the value to the prototype instead of the instance, now all instances will have the customVal property. Besides that there isn't much advantage of using prototype but this method allows you to keep configuration values clear and seperated. You can also extend the prototype as you wish;

Otherclass.prototype = {
firstVal: 2,
secondVal: 2,
exampleObject: {
firstVal: 5,
secondVal: 10
}
}

var k = new Otherclass();
alert(k.prototype.exampleObject.firstVal);
//or
alert(k.exampleObject.firstVal);

Thanks for reading this. My next article will explain the design patterns of javascript. See you next time!

Geen opmerkingen:

Een reactie posten