Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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();
share|improve this question
    
Why are you declaring BaseClass.prototype.talk inside the constructor? –  Joseph Silber Jan 13 '13 at 6:51
    
@JosephSilber: I don't know. Am I not suppose to do it there? Why wouldn't I declare it there? –  acidzombie24 Jan 13 '13 at 6:52
    
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. –  Joseph Silber Jan 13 '13 at 6:54
    
@JosephSilber: Ah, so how would you rewrite all of this code? –  acidzombie24 Jan 13 '13 at 7:00
    
You basically have it all figured out. I changed it around a tiny bit, and posted it below. –  Joseph Silber Jan 13 '13 at 7:17
add comment

1 Answer

up vote 1 down vote accepted
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.

share|improve this answer
    
cool but the talk.apply(this, arguments); looks nasty –  acidzombie24 Jan 13 '13 at 7:32
    
@acidzombie24 - Sure. Wish we didn't need it. –  Joseph Silber Jan 13 '13 at 7:34
    
I'll accept tomorrow or sometime this week. Or whenever I remember which shouldnt be that long –  acidzombie24 Jan 13 '13 at 8:03
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.