Search code examples
javascriptobjectextend

Clone and extend object in jQuery?


Ok, so here is the basics of what I want to do:

var Hi = function(name){
    this.name = name;
};

Hi.prototype = {
    message: function(){
        $('body').append('Hi '+this.name);
    }
};

var hi = new Hi('There ');

Which works fine, but now I want to copy it so I can change it to say "Bye",

var Bye = Hi;
Bye.prototype.message = function(){
    $('body').append('Bye '+this.name);
};

var bye = new Bye('There');

so then to get the output of Hi There Bye There I thought that this should work:

hi.message();
bye.message();

but instead the output is Bye There Bye There aka my modifications overwrite the original object.

How can I get this to work as I expect? note, jQuery/ jQuery UI solutions are fine, but I would like both a vanilla and a jQuery version to understand what's going on!

jsFiddle of my code: http://jsfiddle.net/YGa7p/


Solution

  • The line

    var Bye = Hi;
    

    does simply reference your original function, it does not copy. Usually you do

    var Hi = function(name){
        this.name = name;
    };
    
    Hi.prototype.message = function() {
        $('body').append('Hi '+this.name);
    };
    
    var Bye = function(name){
        Hi.call(this, name); // re-call base constructor
    };
    
    Bye.prototype = new Hi(); // create base object
    
    // overwrite Hi's message
    Bye.prototype.message = function() {
        $('body').append('Bye '+this.name);
    };
    
    var hi = new Hi("there");
    var bye = new Bye("there");
    
    // See also instanceof:
    
    // hi instanceof Hi      // true
    // hi instanceof Object  // true
    
    // bye instanceof Bye    // true
    // bye instanceof Hi     // true
    // bye instanceof Object // true
    

    http://jsfiddle.net/YGa7p/1/.

    In javaScript it's difficult to do OOP. To make derived objects you will get into trouble using 'simple' methods, at least in Level 3...n inheritance. Please read my article on V javaScript class functions, if you're interested in extended inheritance in javaScript.