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\$
5
  • \$\begingroup\$ Why are you declaring BaseClass.prototype.talk inside the constructor? \$\endgroup\$ Commented Jan 13, 2013 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\$ Commented Jan 13, 2013 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\$ Commented Jan 13, 2013 at 6:54
  • \$\begingroup\$ @JosephSilber: Ah, so how would you rewrite all of this code? \$\endgroup\$ Commented Jan 13, 2013 at 7:00
  • \$\begingroup\$ You basically have it all figured out. I changed it around a tiny bit, and posted it below. \$\endgroup\$ Commented Jan 13, 2013 at 7:17

1 Answer 1

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\$
2
  • \$\begingroup\$ cool but the talk.apply(this, arguments); looks nasty \$\endgroup\$ Commented Jan 13, 2013 at 7:32
  • \$\begingroup\$ @acidzombie24 - Sure. Wish we didn't need it. \$\endgroup\$ Commented Jan 13, 2013 at 7:34

You must log in to answer this question.