我在用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>]'我相信这是因为我在prototype声明中包含了私有变量。如果我将prototype声明移动到构造函数中,一切都会正常工作,但这只是掩盖了这样一个事实:通过为每个对象创建一个新的原型,我的对象似乎正在影响原型的属性,而不是它们自己。下面是我的相关代码:
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;
})();发布于 2013-07-05 00:37:17
首先:在内部工具变量定义中,“that =beget(ProtoTool);”你的意思一定是“var that=beget(ProtoTool);”
您的代码中发生了什么?:
对工具定义进行评估,以便为工具赋值。在此评估过程中,围绕protool进行了闭合。
但是这个闭包只有一次,在这个评估过程中:以后对protool的所有调用(通过调用以protools为原型的'that‘)都会改变这个第一个也是唯一一个闭包的值。
这就是为什么你会看到这样的行为:最近看到的对象将会得到所有的关注,因为它更新了闭包的值。
解决方案是在“tool”内部var函数定义中使用正确的闭包made。
但如果可以的话,我建议完全使用经典的javascript类定义,然后使用new运算符,我相信这更容易编码/理解/调试。
另一个rq :在最新的javascript规范(1.8.6)中获得=== Object.create
https://stackoverflow.com/questions/17474520
复制相似问题