好的,我怀疑这是一种独特的情况,所以无论是有人已经这样做了,或者有人认为这是不可能的,至少在我问的方式。Javascript原型 - 需要帮助添加帮助器原型
我有2个原型变量(功能),一个是父母,另一个是帮手。我想要做的是从助手内引用父对象,以便每个父对象的每个实例都可以使用助手,同时允许助手实质上扩展父对象。我使用jQuery和JavaScript。
这里有一个简单的例子:
var Parent = function(identity) {
this.identity = identity;
this.group = $(this.identity);
this.helper = new Helper(this);
return this;
};
Parent.prototype = {
_setup : function(dolisten) {
dolisten = dolisten || false;
var that = this;
that.group.each(function(i) {
if ($(this).data('key') !== 'undefined') {
that.elems[i] = new Object();
that.elems[i].key = parseInt($(this).data('key'));
// build out rest of elems object
}
});
if (dolisten) {
this._listen();
}
},
_listen : function() {
var that = this
$('body').on('click tap', that.identity, function() {
that.helper._showbusy(this, true);
// do some other stuff
}
}
};
var Helper = function(reference) {
this.reference = reference;
};
Helper.prototype = {
_showbusy : function(elem, isbusy) {
console.log(this.reference);
// do some stuff to elem
},
};
这工作,但来自其自身.helper节点内产生实质上无限引用父。所以,如果没有每次都实际传递父对象(希望只创建一个引用点,上面的代码似乎会导致引用“循环”?),这可以优雅地完成吗?
最后,我想是一个简单的:
var obj = new Parent('.myClass');
console.log(obj);
// result : Parent { identity:'.myClass', group: [Object object], helper: {reference : *Parent without helper key included, which is where the looping seems to occur}, etc...
编辑:暂时,我诉诸传递由助手需要父母的特定按键。这可以防止助手无限级联到父级副本和自身,但是更优雅的解决方案,其中帮助者可以访问整个父级,而不是只传递特定的键,而不需要级联助手引用父级成为父级 - >助手 - > parent - > helper - > parent - > etc ...
http://javascript.crockford.com/private。html有一个阅读。为你的“助手”使用“特权”对象 – Mike 2014-10-01 17:29:15
你想要什么? '家长'赠送'助手',反之亦然? – 2014-10-01 17:45:41
我希望帮助器的每个实例都可以使用帮助器的功能 - 所以我希望帮助器可以扩展父代,但可能有一个实例,我说,兄弟姐妹是父代的兄弟,在辅助器中也需要一些功能,其中helper使用任何函数调用它的私有变量(在父节点中的'this'!'this'在兄弟节点中,但'父'或兄弟节点中的'this'可由助手访问)。 – Lazerblade 2014-10-01 18:13:03