1
\$\begingroup\$

I'm sure this can be done in less lines and in a more clean way?

function BaseClass() {
  BaseClass.prototype.talk = function () {
    alert("I'm BaseClass");
  }
}

function MyClass() {
  BaseClass.call(this);
}
MyClass.prototype = new BaseClass();
MyClass.base = {};
MyClass.base.talk = MyClass.prototype.talk;
MyClass.prototype.talk = function () {
  alert("I'm MyClass");
  MyClass.base.talk();
}

var a = new MyClass();
a.talk();
\$\endgroup\$
  • \$\begingroup\$ Why are you declaring BaseClass.prototype.talk inside the constructor? \$\endgroup\$ – Joseph Silber Jan 13 '13 at 6:51
  • \$\begingroup\$ @JosephSilber: I don't know. Am I not suppose to do it there? Why wouldn't I declare it there? \$\endgroup\$ – user21077 Jan 13 '13 at 6:52
  • \$\begingroup\$ Because then you're recreating the function every time you create a new object. The prototype is used to store functions that are shared between your objects. \$\endgroup\$ – Joseph Silber Jan 13 '13 at 6:54
  • \$\begingroup\$ @JosephSilber: Ah, so how would you rewrite all of this code? \$\endgroup\$ – user21077 Jan 13 '13 at 7:00
  • \$\begingroup\$ You basically have it all figured out. I changed it around a tiny bit, and posted it below. \$\endgroup\$ – Joseph Silber Jan 13 '13 at 7:17
1
\$\begingroup\$
function BaseClass () {}

BaseClass.prototype.talk = function () {
    alert("I'm BaseClass");
}

function MyClass() {
    BaseClass.call(this);
}

MyClass.prototype = new BaseClass();
MyClass.base = BaseClass.prototype;

MyClass.prototype.talk = function () {
    alert("I'm MyClass");
    MyClass.base.talk.apply(this, arguments);
}

var a = new MyClass();
a.talk();

To make all this easier on yourself, don't re-invent the wheel. Look into John Resig's tiny inheritance library: Simple JavaScript Inheritance.

\$\endgroup\$
  • \$\begingroup\$ cool but the talk.apply(this, arguments); looks nasty \$\endgroup\$ – user21077 Jan 13 '13 at 7:32
  • \$\begingroup\$ @acidzombie24 - Sure. Wish we didn't need it. \$\endgroup\$ – Joseph Silber Jan 13 '13 at 7:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy