我一直在努力破解这个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()
?我还能做些什么来清理这个烂摊子?
感谢。
答案 0 :(得分:1)
创建mmlnum
对象并在此处为每个n-var使用$.extend
并不是那么糟糕。如果不使用它们,那么设置你的n-vars就必须看起来像这样:
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];
};
......这两种方式都不太可读,也不那么干。即使在此之前还有很多需要清理的地方,我认为你应该保留你所引用的部分。
答案 1 :(得分:1)
让mmlnum
调用基础构造函数,然后扩展prototype
。 Example 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
。