...

View Full Version : Java Funciton question



erikkl2000
01-14-2007, 09:41 PM
Hi,


I am studing some code that a developer on the net wrote and i am in need of some understanding of how a specific funciton is built..


Below where the funciton looks like so: Object.prototype.clone = function()
Is the funciton actually setting a property of some sort in the Object.prototype.clone ?? I have notice this style when writing javaScript and just need someone to tell me that is going on here..

Thanks alot
Erik


Object.prototype.clone = function()
{
var o = {};
var property;

for (property in this) {
if (typeof this[property] == "object")
o[property] = this[property].clone();
else
o[property] = this[property];
}

return o;
}

Array.prototype.clone = function()
{
var a = [];
var i;

for (i = 0; i < this.length; i++) {
if (typeof this[i] == "object")
a[i] = this[i].clone();
else
a[i] = this[i];
}

return a;
}

shyam
01-15-2007, 02:50 AM
all javascript objects inherit from the Object. And a prototype function is one that gets bound to all the subsequent objects that are created. In other words its a way of dynamically adding instance methods to an object.

The example you've provided is adding a clone method to all the objects that will be created henceforth. Consider this



var myObj = {attr1:'something'}
var myClone = myObj.clone(); // will throw an error that the method is not defined

but the same when done this way


Object.prototype.clone = function()
{
//...
return o;
}
var myObj = {attr1:'something'}
var myClone = myObj.clone(); // will work no problem at all



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum