有人知道如何创建一个返回元素而不丢失其原型(prototype)的函数吗?
我正在尝试创建函数来创建新元素并将其作为元素返回。这个函数将有一个方法来操作那个元素。当我返回该元素时,原型(prototype)将不起作用。如果我不使用 return
在该函数中,原型(prototype)正常工作,但函数返回 this
目的。看这段代码:
function ObjEl(tagName, id) {
'use strict';
this.node = document.createElement(tagName);
if (typeof id === 'string' && id.match(/^[a-zA-Z\d\_\-]+$/)) {
this.node.setAttribute('id', id);
}
// return this.node;
}
ObjEl.prototype.atr = function (key, val) {
'use strict';
this.node.setAttribute(key, val);
return this;
};
如果我取消注释 return this.node;
, 当我调用 test = ObjEl('div', 'test');
它正在返回 <div id="test"></div>
,但此代码不起作用:
test = ObjEl('div', 'test').remove();
最佳答案
看起来很奇怪,但这能实现您想要做的事情吗?
var ObjEl=function ObjEl(tagName, id) {
'use strict';
this.node = document.createElement(tagName);
if (typeof id === 'string' && id.match(/^[a-zA-Z\d\_\-]+$/)) {
this.node.setAttribute('id', id);
}
// return this.node;
}
ObjEl.prototype.atr = function (key, val) {
'use strict';
this.node.setAttribute(key, val);
return this;
};
var oldObjEl=ObjEl;
ObjEl=function (){
return new oldObjEl(arguments[0],arguments[1]);
}
关于javascript - 在不丢失原型(prototype)的情况下返回函数的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19755243/