3

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.

3
  • i think this will be useful stackoverflow.com/questions/13745021/… Commented Apr 23, 2018 at 13:06
  • Are you using a third-party library here, EG Prototype? That first line does not look like vanilla JS. Maybe worth adding a tag for that if it's the case. And it would be good to indicate to people helping that you do or don't want to stick to using that lib and its methods. Commented Apr 23, 2018 at 13:10
  • Yes, "I am" using prototype, added the tag, thanks. Basically it is a magento2 thing. Commented Apr 23, 2018 at 13:12

1 Answer 1

2

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();

Sign up to request clarification or add additional context in comments.

1 Comment

The problem is that I have nothing to do with the prototype. The object has already created. I need to use an existing object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.