如何解决重构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];
};
...这两种方法的可读性和干性都较低。即使在此之前还有很多要清理的地方,我认为您也应该保留引用的部分。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。