如何从子对象调用父函数?

时间:2019-05-03 12:40:32

标签: javascript object inheritance

我有这样的代码:

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');
        }
    }
}

并出现错误:“未捕获的TypeError:无法读取未定义的属性'call'”。我想用自定义方法覆盖对象方法,从该方法调用父方法,然后添加一些代码。我的错误在哪里?

P。 S.阅读评论链接上的文章,并更改代码,如下所示:

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

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

window['myThings'] = {

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

现在我有一个错误:foo不是函数...

P。 P. S.更改代码如下:

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

现在:传递给构造函数的arg未存储在someVar中或未从中读取...

1 个答案:

答案 0 :(得分:0)

解决方案在这里:

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