我在用 Javascript 编写对象构造函数时遇到问题。当我在一个实例化对象上调用函数时,它总是返回实例化对象的值。流程是这样的:
blue = tool('blue');
blue.jDom(); // returns '[<div id="blue" class="tool">...</div>]'
red = tool('red');
red.jDom(); // returns '[<div id="red" class="tool">...</div>]'
blue.jDom(); // returns '[<div id="red" class="tool">...</div>]'
我相信这是由于我在原型声明中包含的私有变量。如果我将原型声明移到构造函数中,一切正常,但这只是掩盖了这样一个事实,即我的对象似乎通过为每个对象创建一个新原型来影响原型的属性,而不是它们本身。这是我的相关代码:
function beget(oPrototype) {
function oFunc() {};
oFunc.prototype = oPrototype;
return new oFunc()
};
var tool = (function (){
var protoTool = function(){
var oTool = {},
that = this,
_bVisible = true,
_oParentPane = 'body',
_aoComponents,
_sName = 'tool',
_sSelector = '#' + _sName,
_jDomElement;
// this is the private tab object, needs to be refactored
// descend from a single prototype
function _tab() {
var oTab = {},
_sHtml = '<li><a href="' + _sSelector + '">' + _sName + '</a></li>',
_jDomElement = $(_sHtml);
function jDom() {
return _jDomElement;
}
oTab.jDom = jDom;
return beget(oTab);
};
// this builds the jDom element
function _jBuild() {
var sHtml = '<div id="' + _sName + '" class="tool"></div>';
_jDomElement = $(sHtml)
return _jDomElement;
};
// this returns the jQuery dom object
function jDom() {
if (typeof _jDomElement === 'undefined') {
_jBuild();
}
return _jDomElement;
};
function configure (oO){
if (typeof oO !== 'undefined') {
if (typeof oO === 'string') {
var name = oO;
oO = Object();
oO.sName = name;
}
_bVisible = oO.bVisible || _bVisible,
_oParentPane = oO.oParentPane || _oParentPane,
_aoComponents = oO.aoComponents || _aoComponents,
_sName = oO.sName || _sName,
_sSelector = '#' + _sName,
_jDomElement = undefined;
_oTab = _tab();
_oTab.jDom()
.appendTo(jDom())
.draggable({
revert: 'invalid',
containment: '#main',
distance: 10,
});
}
};
oTool.tMove = tMove;
oTool.bVisible = bVisible;
oTool.uOption = uOption;
oTool.jDom = jDom;
oTool.configure = configure;
return oTool;
}();
var tool = function (oO) {
that = beget(protoTool);
that.configure(oO);
that.configure = undefined;
return that;
};
return tool;
})();