Search code examples
javascriptobjectprototype

Extend an existsing object method


I have an object:

MyObj = new Class.create();
MyObj.prototype = {
    initialize: function () {
        this.myArg = null;
    },

    setArg: function(arg) {
        this.myArg = arg;

    },

    showArg: function () {
        alert(this.myArg);
    }
};

var x = new MyObj();
x.setArg('Something');
x.showArg();

x.setArg = function(arg) {
    //how to call here the original??
    alert('Here is my custom code')
}

It is created in a code what I can not overwrite.

What I want to do is to extend this existing object like this:

x.setArg = function(arg) {
        this.myArg = arg + ' a new cake';
}

I just do not want to copy the original code.

UPDATE:

I have nothing to do with the prototype. The object has already created.


Solution

  • You have two options here

    Option One

    Override only the method

    var MyObj = function(){};
    MyObj.prototype = {
        initialize: function () {
            this.myArg = null;
        },
    
        setArg: function(arg) {
            this.myArg = arg;
    
        },
    
        showArg: function () {
            alert(this.myArg);
        }
    };
    
    var oldMethod = MyObj.prototype.setArg;
    MyObj.prototype.setArg = function(arg) {
        oldMethod.call(this,arg)
        console.log(arg)
    }
    
    
    var x = new MyObj();
    x.setArg('Something');
    x.showArg();

    Option Two

    Extend the object then override any method you want

    var MyObj = function(){};
    MyObj.prototype = {
        initialize: function () {
            this.myArg = null;
        },
    
        setArg: function(arg) {
            this.myArg = arg;
    
        },
    
        showArg: function () {
            alert(this.myArg);
        }
    };
    
    
    var MyNewObject = function() {
    }
    
    MyNewObject.prototype = new MyObj()
    MyNewObject.prototype.setArg = function(arg) {
        MyObj.prototype.setArg.call(this,arg)
        console.log(arg)
    }
    
    
    var x = new MyNewObject();
    x.setArg('Something');
    x.showArg();