2

I am trying to extend an object, and I want to modify a method of the first, not to override it. I don't think this is clear so here is an example:

var object1 = {
    whatever : function(){
        console.log('first object method');
    }
}

var object2 = {
    whatever : function(){
        console.log('second object method');
    }
}

var object = $.extend(true, object1, object2);

object.whatever();

This example will output second object method, but what I want is that it ouput first object method and second object method.

Is there a way to do this?

gdoron
  • 147,333
  • 58
  • 291
  • 367
romainberger
  • 4,563
  • 2
  • 35
  • 51
  • It's what the example is showing: when you define two method with the same name in the two object, the first is not triggered. I want something like `parent::whatever()` in PHP – romainberger Jun 06 '12 at 22:12
  • No, `extends` doesn't "extends" functions, this is not what it was designed to do. – gdoron Jun 06 '12 at 22:15
  • `$.extend` doesn't work that way. It just replaces properties when there are duplicates. – gen_Eric Jun 06 '12 at 22:26
  • Although JS has no in-built way of calling a superclass, you can do it using a technique described [here](http://www.kevlindev.com/tutorials/javascript/inheritance/inheritance10.htm). – Jeff Watkins Jun 06 '12 at 22:14

1 Answers1

3

Javascript uses prototypal inheritance, so you can make object2 inherit object1's properties and methods by doing

object2.prototype=object1;

this means that object2 will inherit all the properties and methods of object1, and any overwritten methods can be accessed at object2.prototype.method()

so parent::whatever(); is equivalent to this.prototype.whatever(); when calling from the scope of object2.


var object1 = {
    whatever : function(){
        console.log('first object method');
    }
}

var object2 = {
    whatever : function(){
        console.log('second object method');
        this.prototype.whatever(); // Equivalent to parent::whatever(); 
    }
}

object2.prototype=object1; // Makes object2 inherit object1's properties and methods

object2.whatever(); // "second object method" "first object method"
Cameron Martin
  • 5,952
  • 2
  • 40
  • 53
  • Where do I have to add `object2.prototype=object1;`? In the second object or after? – romainberger Jun 06 '12 at 22:30
  • Not as simple as I would like because in the app I am working on the first object will be extended several times, but it works, thanks! – romainberger Jun 06 '12 at 22:38
  • If you need to extend it several times, use a prototype chain. So object2.prototype=object1; object3.prototype=object2; Object 3 will inherit first from object2, then from object1. – Cameron Martin Jun 06 '12 at 22:52