Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jan 2007
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Java Funciton question

    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;
    }

  • #2
    Senior Coder shyam's Avatar
    Join Date
    Jul 2005
    Posts
    1,563
    Thanks
    2
    Thanked 163 Times in 160 Posts
    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

    Code:
    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
    Code:
    Object.prototype.clone = function()
    {
    //...
    return o;
    }
    var myObj = {attr1:'something'}
    var myClone = myObj.clone(); // will work no problem at all


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •