继承和模块模式 [英] Inheritance and module pattern

查看:77
本文介绍了继承和模块模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图用这种方式用模块模式实现继承:

I'm trying to implement the inheritance with the module pattern in this way:

Parent = function () {

    //constructor
    (function construct () {
        console.log("Parent");
    })();

    // public functions
    return this.prototype = {

        test: function () {
            console.log("test parent");
        },


        test2: function () {
            console.log("test2 parent");
        }

    };
};


Child = function () {

    // constructor
    (function () {
        console.log("Child");
        Parent.call(this, arguments);
        this.prototype = Object.create(Parent.prototype);
    })();


    // public functions
    return this.prototype = {

        test: function()
        {
            console.log("test Child");
        }

    }

};

但我不能从孩子的实例调用 test2()

but I can't to call from child's instance the test2().

var c = new Child();
c.test2(); // c.test2 is not a function

我错了什么?

推荐答案

您没有以正确的方式使用模块模式。不知何故,您的构造函数被称为立即调用的函数表达式( IIFE ),模块关闭不是。它应该是相反的。

You're not using the module pattern in the correct way. Somehow, your "constructor" is called as an immediately-invoked function expression (IIFE), and the module closure is not. It should be the other way round.

此外,你不能分配给 this.prototype 。要创建所有实例将继承的原型对象,您需要分配构造函数 prototype 属性( 关键字甚至指向你的情况下的全局窗口对象。)

Also, you can't assign to this.prototype. To create the prototype object from which all instances will inherit, you will need to assign to the prototype property of the constructor function (the this keyword even pointed to the global window object in your case).

你应该返回构造函数,而不是原型对象,一旦你拥有它就从IIFE。

And you should return the constructor function, not the prototype object, from the IIFE as soon as you have it.

Parent = (function () {
    // constructor
    function construct () {
        console.log("Parent");
    };

    // public functions
    construct.prototype.test = function () {
        console.log("test parent");
    };
    construct.prototype.test2 = function () {
        console.log("test2 parent");
    };

    return construct;
})();


Child = (function () {
    // constructor
    function construct() {
        console.log("Child");
        Parent.apply(this, arguments);
    }

    // make the prototype object inherit from the Parent's one
    construct.prototype = Object.create(Parent.prototype);
    // public functions
    construct.prototype.test = function() {
        console.log("test Child");
    };

    return construct;
})();

这篇关于继承和模块模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆