Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling method using JavaScript prototype

Is it possible to call the base method from a prototype method in JavaScript if it's been overridden?

MyClass = function(name){
    this.name = name;
    this.do = function() {
        //do somthing 
    }
};

MyClass.prototype.do = function() {  
    if (this.name === 'something') {
        //do something new
    } else {
        //CALL BASE METHOD
    }
};
like image 557
Mark Clancy Avatar asked Oct 17 '22 02:10

Mark Clancy


2 Answers

I did not understand what exactly you're trying to do, but normally implementing object-specific behaviour is done along these lines:

function MyClass(name) {
    this.name = name;
}

MyClass.prototype.doStuff = function() {
    // generic behaviour
}

var myObj = new MyClass('foo');

var myObjSpecial = new MyClass('bar');
myObjSpecial.doStuff = function() {
    // do specialised stuff
    // how to call the generic implementation:
    MyClass.prototype.doStuff.call(this /*, args...*/);
}
like image 207
Christoph Avatar answered Oct 19 '22 14:10

Christoph


Well one way to do it would be saving the base method and then calling it from the overriden method, like so

MyClass.prototype._do_base = MyClass.prototype.do;
MyClass.prototype.do = function(){  

    if (this.name === 'something'){

        //do something new

    }else{
        return this._do_base();
    }

};
like image 24
Ramuns Usovs Avatar answered Oct 19 '22 16:10

Ramuns Usovs