在命名空间内使用继承

时间:2014-10-27 00:55:57

标签: javascript oop

在命名空间内,我有两个对象定义(AKA:“classes”)。

¿如何让一个类继承命名空间内的另一个类?

首先,我尝试了这个:

var ns = { // the namespace
    OneClass : function() { 
        console.log("Instance of OneClass has been constructed");
        this.foo = ":)";
    },

    Inherited : function() {
        this.anotherFoo = "):";
    },

    Inherited.prototype : new this.OneClass,
    Inherited.prototype.constructor = this.Inherited
};

但是这会在第11行产生错误:SyntaxError: missing : after property id

所以我把代码更改为了这个,它起作用了:

var ns = { // the namespace
    OneClass : function() { 
        console.log("Instance of OneClass has been constructed");
        this.foo = ":)";
    }

    Inherited : function() {
        this.anotherFoo = "):";
    }
};

ns.Inherited.prototype = new ns.OneClass();
ns.Inherited.prototype.constructor = ns.Inherited;

无论如何,我不喜欢这个解决方案,因为继承声明必须在命名空间的末尾声明,这会使代码“混乱”。

所以我宁愿让继承声明尽可能接近Inherited对象定义。

0 个答案:

没有答案