2011-05-23 53 views
0

我挣扎着,黑了这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, {}, mmlnum), 
    n3 = jQuery.extend(true, {}, mmlnum), 
    n4 = jQuery.extend(true, {}, mmlnum); 

n1.val = 6; 
n2.val = 7; 
n3.val = 8; 
n4.val = 9; 

如何获得new()n1工作 - n4,而不必使用extend()?我还能做些什么来清理这个混乱?

谢谢。

回答

1

品牌mmlnum调用基础构造函数,然后扩展prototypeExample on jsFiddle.

function mmlnum() 
{ 
    mmlfunc.call(this, 
       "Value", 
       function() { return this.val; }, 
       [ '<mn>', '</mn>' ]); 
} 

jQuery.extend(true, mmlnum.prototype, mmlfunc.prototype); 

,然后改变你的增值经销商向

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

Inheritance on MDC.

+0

您的解决方案工作得很好。与C++/C#/ Java相比,我承认在Javascript对象模型方面相当困惑,但我会通过它。 – Reinderien 2011-05-26 00:37:22

1

在这里创建mmlnum对象并为每个n-var使用$.extend并不坏。如果不使用它们,然后设置你的正增值经销商将不得不像这样的事情:

var n1 = new mmlfunc('Value', 
        function() { return this.val; }, 
        [ '<mn>', '</mn>' ])), 
    n2 = new mmlfunc('Value', 
        function() { return this.val; }, 
        [ '<mn>', '</mn>' ])), 
    n3 = new mmlfunc('Value', 
        function() { return this.val; }, 
        [ '<mn>', '</mn>' ])), 
    n4 = new mmlfunc('Value', 
        function() { return this.val; }, 
        [ '<mn>', '</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]; 
      }; 

...这既是这样的可读性和少干。即使在这之前有很多要清理的东西,我认为你应该保留原来所引用的部分。