\$\begingroup\$
\$\endgroup\$
5
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();
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
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.
answered Jan 13, 2013 at 7:16
-
\$\begingroup\$ cool but the
talk.apply(this, arguments);
looks nasty \$\endgroup\$user21077– user210772013年01月13日 07:32:27 +00:00Commented Jan 13, 2013 at 7:32 -
\$\begingroup\$ @acidzombie24 - Sure. Wish we didn't need it. \$\endgroup\$Joseph Silber– Joseph Silber2013年01月13日 07:34:45 +00:00Commented Jan 13, 2013 at 7:34
default
BaseClass.prototype.talk
inside the constructor? \$\endgroup\$