Sunday, March 27, 2011

Use prototype to make javascript object oriented

Unlike other object oriented language, javascript does not support the common way of defining data member or function member. However, this can be supported in javascript by using prototype.
For javascript, when a function is defined, it automatcally gets a data member of prototype, which also has a constructor method by default- i.e the function itself. The constructor is used to create the instance of the object. If any data members or function members are defined on this prototype object, then all instances created by the function will automatically have those data members and function members defined, similar to other object oriented lanaguages, the code is shown below,
function f(){
}
f.prototype.datamember=3.14159;

// create the object method
function f2(o){
alert(o);
}
f.prototype.funcmember=f2;

Note for prebuild types, only object, image, string, data and array can have their prototype changed to add new data members and function members, which means you can extend new function into those prebuild types. With the following code, then all instance of object will have the newprop as 123.
Object.prototype.newprop = "123";

Note if a same named property is defined in both object instance itself and object propotype, then the object instance property will take priority.
Jonathan

No comments:

Post a Comment