重构Javascript继承结构

问题描述

| 我一直在努力并入侵了这个Javascript,使其正常工作:
function mmlfunc(name,evalcallback,mmlparts)
{
    this.name = name;
    // ...
}
mmlfunc.prototype.evalFunc = function()
{
    return this.evalcallback(this.args);
};
mmlfunc.prototype.getMML = function()
{
    var mml = this.mmlparts[0];
    // ...
    return mml;
}

// ...

mmlnum = jQuery.extend(true,{},new mmlfunc(\'Value\',function() { return this.val; },[ \'<mn>\',\'</mn>\' ]));
mmlnum.getMML = function()
{
    return this.mmlparts[0] + this.val + this.mmlparts[1];
}

// ...
var n1 = jQuery.extend(true,mmlnum),n2 = jQuery.extend(true,n3 = jQuery.extend(true,n4 = jQuery.extend(true,mmlnum);

n1.val = 6;
n2.val = 7;
n3.val = 8;
n4.val = 9;
如何使
new()
n1
-
n4
上工作,而不是必须使用
extend()
?我还可以采取什么措施来清理混乱? 谢谢。     

解决方法

使
mmlnum
调用基本构造函数,然后扩展
prototype
。 jsFiddle上的示例。
function mmlnum()
{
    mmlfunc.call(this,\"Value\",function() { return this.val; },[ \'<mn>\',\'</mn>\' ]);
}

jQuery.extend(true,mmlnum.prototype,mmlfunc.prototype);
然后将您的var更改为
var n1 = new mmlnum(),n2 = new mmlnum(),n3 = new mmlnum(),n4 = new mmlnum();

n1.val = 6;
n2.val = 7;
n3.val = 8;
n4.val = 9;
使用
alert(n1.name)
将显示
Value
。 在MDC上继承。     ,创建
mmlnum
对象并在此处为每个n-var使用t12ѭ还不错。如果不使用它们,那么设置您的n-var必须看起来像这样:
var n1 = new mmlfunc(\'Value\',\'</mn>\' ])),n2 = new mmlfunc(\'Value\',n3 = new mmlfunc(\'Value\',n4 = new mmlfunc(\'Value\',\'</mn>\' ]));
n1.getMML = function() {
                return this.mmlparts[0] + this.val + this.mmlparts[1];
            };
n2.getMML = function() {
                return this.mmlparts[0] + this.val + this.mmlparts[1];
            };
n3.getMML = function() {
                return this.mmlparts[0] + this.val + this.mmlparts[1];
            };
n4.getMML = function() {
                return this.mmlparts[0] + this.val + this.mmlparts[1];
            };
...这两种方法的可读性和干性都较低。即使在此之前还有很多要清理的地方,我认为您也应该保留引用的部分。