【问题标题】:How to call parent function from descedant object? [duplicate]如何从后代对象调用父函数? [复制]
【发布时间】:2019-05-03 12:40:32
【问题描述】:

我有这样的代码:

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

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

P。 S. 从 cmets 阅读链接上的文章并更改代码如下:

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

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

window['myThings'] = {

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

现在我有一个错误: foo is not a function...

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 中或未从中读取...

【问题讨论】:

  • Thing 原型上没有任何内容。这不是你在 JS 中定义构造函数的方式
  • 您从构造函数返回一个对象,因此该构造函数的实例不会继承自 Thing.prototype
  • “什么是 JavaScript 中的 'new' 关键字可能重复? - Jared Smith 1 小时前” - 这不能解决问题...

标签: javascript object inheritance


【解决方案1】:

解决方案在这里:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    • 2021-11-15
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多