0

I have code like this:

function Thing() {

    function foo() {
        alert('1');
    }
    return { foo : foo }

}

window['myThings'] = {

    bar : function() {
        let t = new Thing();
        t.foo = function() {
            Thing.prototype.foo.call(this);
            alert('2');
        }
    }
}

And have error: "Uncaught TypeError: Cannot read property 'call' of undefined". I want override object method with custom method, from which call parent method and then add some code. Where is my mistake?

P. S. Read article on the link from the comments and change code like this:

Thing = function () {     
    this.someVar = 1;
    foo();
}

Thing.foo = function() {
     alert('1');
}

window['myThings'] = {

    bar : function() {
        let t = new Thing();
        t.foo();
    }
}

And now i have an error: foo is not a function...

P. P. S. Change code like this:

    function Thing() {};
    Thing.prototype = function (arg) {     
        this.someVar = arg;
        this.foo();
    }

    Thing.prototype.foo = function() {
        alert('1');
    }

    window['myThings'] = {

        bar : function() {
            let t = new Thing(1);
            t.foo();
        }
    }
    myThings.bar();

And now: arg passed to constructor not stored in someVar or not readed from it...

Alex Shul
  • 500
  • 7
  • 22
  • 2
    There's nothing on Thing prototype. That's not how you define constructors in JS – Jared Smith May 03 '19 at 12:42
  • You are returning a object from a constructor, So instance of that constructor will not inherit from `Thing.prototype` – Maheer Ali May 03 '19 at 12:42
  • "Possible duplicate of What is the 'new' keyword in JavaScript? – Jared Smith 1 hour ago" - This not solve the problem... – Alex Shul May 03 '19 at 14:08

1 Answers1

0

Solution is here:

    function Thing(arg) {
        var private = 'private';
        this.public = 'public';           

        this.init = function(arg) {
            private = arg;
            this.foo();
            alert(private);
        }
        this.foo = function() {
            alert('foo');
        }

        this.init(arg);
    };        

    window['myThings'] = {

        things : [],

        bar : function() {
            this.things[0] = new Thing('privateArg'); 

            function AnotherThing(arg) {
                Thing.call(this, arg);
                var parentFoo = this.foo;
                this.foo = function() {
                    //  Call parent method
                    parentFoo();
                    //  Run custom code
                    alert('foo foo');
                }
            }

            //  Parent init called with parent foo() method
            this.things[1] = new AnotherThing(2);
            //  Customized foo() called
            this.things[1].foo();
        }
    }
    myThings.bar();
Alex Shul
  • 500
  • 7
  • 22