gpt4 book ai didi

Javascript 原型(prototype) - 需要帮助添加 Helper 原型(prototype)

转载 作者:行者123 更新时间:2023-11-28 00:56:38 27 4
gpt4 key购买 nike

好吧,我怀疑这是一个独特的情况,所以要么有人这样做了,要么有人认为这是不可能的,至少以我所要求的方式。

我有 2 个原型(prototype)变量(函数),一个是父变量,另一个是助手。我想做的是从助手中引用父级,以便每个父级的每个实例都可以利用助手,同时允许助手本质上扩展父级。我正在使用 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 节点中创建对 Parent 的本质上无限的引用。因此,无需每次都实际传递父级(希望仅创建一次引用点,上面似乎会导致引用“循环”?),这可以优雅地完成吗?

最后,我想要的是一个简单的:

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...

编辑:目前,我正在诉诸传递助手所需的父级的特定键。这可以防止助手无限级联到父级及其自身的副本,但这是一个更优雅的解决方案,其中助手可以访问整个父级,而不仅仅是传递的特定键,而无需级联助手对父级的引用成为父级 -> 助手 -> 父级 -> 助手 -> 父级 -> 等等...

最佳答案

您所指的称为循环引用,它被定义为两个相互引用的数据结构。

var a = {value: 'A'};
var b = {value: 'B'};
a.b = b;
b.a = a;

console.log(a.b.a.b.a.b.a.b.a.b.a.b.value); // 'B'

在大多数情况下,这实际上是可以的。现代垃圾收集器足够聪明,可以在对象过期时清理它,因此应该很好地处理内存。很多 JS 代码都会使用循环引用创建对象。

您将遇到的最大问题是,如果您想将对象编码为 JSON,或者对对象执行任何递归操作。

// continued code form above
JSON.stringify(a);
// TypeError: Converting circular structure to JSON

因为 JSON 生成是一个递归过程,所以它会深入到每个属性,这些属性会被锁定在循环引用中并生成无限量的 JSON。

There are some ways handle that though

关于Javascript 原型(prototype) - 需要帮助添加 Helper 原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26147067/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com