Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Extend and Access Superclass

Is there a way to access the super object when extending objects using $.extend?

I would like to extend an object, override a method, but call the overridden superclass method in the subclass method.

like image 678
Steve Avatar asked May 06 '10 16:05

Steve


3 Answers

No, because there is no superclass. According to the docs for jQuery.extend:

Description: Merge the contents of two or more objects together into the first object.

In order to call a "superclass" method, you would have to keep a copy of the "superclass" around somewhere (perhaps as a parameter in the "descendant" object), and call the method directly on the "superclass".

like image 126
Justin Ethier Avatar answered Sep 18 '22 11:09

Justin Ethier


If you are looking for javascript inheritance, you may be interested in this post from John Resig.

like image 36
James Westgate Avatar answered Sep 18 '22 11:09

James Westgate


Not directly -- the old method is not longer around (except in the original object).

I've done two things: The first is to make a copy of the old method with a new name in the subclass:

var Super = {
  a: function() {...}
};

var _SubFuncs: {
  _superA: Super.a

  a: function() {... this._superA(...) ... }
};

var Sub = $.extend(false, Super, _SubFuncs);

The other thing I've done when appropriate is to use the template pattern and have the super class call a method that for it has no behavior. The subclass then add behavior to the empty method. This only works if your call structure is such that "holes" can be added appropriately.

Edit: In my case, I was really trying to stick with prototypal objects so I was avoiding a general solution that makes my objects more class-like.

like image 29
Kathy Van Stone Avatar answered Sep 17 '22 11:09

Kathy Van Stone