最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery - Extend and Access Superclass - Stack Overflow

programmeradmin6浏览0评论

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.

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.

Share Improve this question edited May 6, 2010 at 16:56 Kathy Van Stone 26.3k3 gold badges33 silver badges42 bronze badges asked May 6, 2010 at 16:41 SteveSteve 55.6k34 gold badges99 silver badges145 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

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".

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

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.

If you want to use the class inheritance and call the super class methods, then this blog from John Resig explains it all http://ejohn/blog/simple-javascript-inheritance/

发布评论

评论列表(0)

  1. 暂无评论