0

I want to create a child JS object which passes arguments back to parent constructor and will be able to override parent methods.

I've done the task by a hack, please my fiddle http://jsfiddle.net/glebv/kbvmzg63/3/

Parent constructor:

var Parent = function (name) {
    this.meth1 = function () {
        console.log("Parent meth1 ", name);
    };
    this.meth2 =  function() { 
        console.log('Parent meth2 ', name);
    };
    return this;
}

Please pay attention on "name" argument which is used in the methods.

Child constructor:

var Child = function (name) {
        var child = new Parent(name);
        for (var property in child) {       
                this[property] = child[property];
        }

    this.meth1 =  function () {
        console.log("Child ", name);
    };
    return this;
}

As you see, it's not classical inheritance, it's copy-past methods from the parent to the child. I guess there's more powerful method via prototype inheritance. There's simple acceptance criteria: 1) it should work

childObj = new Child("bla");
childObj.meth1(); //Child bla
childObj.meth2(); //Parent meth2 bla

2) Parent constructor is not changeable because it belongs to external lib.

I've test different solutions but it didn't solve my task. I will appreciate for your suggestions.

UPD

The task is solved, there's solution jsfiddle.net/glebv/kbvmzg63/5

Gleb Vinnikov
  • 458
  • 4
  • 13
  • 1
    Parent.call(this, name) would do. I see you're not using prototype so you can have instance specific private members. More on prototype and constructor functions here: http://stackoverflow.com/a/16063711/1641941 – HMR Jan 28 '15 at 12:12
  • @HMR I know it, but there is a nuance, could you provide me work fiddle for my case. – Gleb Vinnikov Jan 28 '15 at 13:22
  • @HMR, thanks, I found solution, it works properly http://jsfiddle.net/glebv/kbvmzg63/5/ – Gleb Vinnikov Jan 28 '15 at 14:36
  • @GlebVinnikov If you've found a solution, feel free to detail it within an answer (do not just provide a jsfiddle) – Kevin B Jan 28 '15 at 14:40
  • possible duplicate of [Can't get the inherited class functions in JS](http://stackoverflow.com/questions/27606331/cant-get-the-inherited-class-functions-in-js) – JLRishe Jan 28 '15 at 15:03

0 Answers0