繁体   English   中英

Javascript原型-需要帮助来添加Helper原型

[英]Javascript prototype - Need help adding a Helper prototype

好的,我怀疑这是一种独特的情况,所以有人至少做到了这一点,或者有人认为这是不可能的,至少按照我的要求。

我有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节点中创建了对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...

编辑:暂时,我要传递帮助程序所需的父级特定键。 这样可以防止帮助程序无限级联为父级及其自身的副本,但是这是一种更为优雅的解决方案,其中,帮助程序可以访问整个父级而不是仅传递特定的键,而无需级联帮助程序对父级的引用而成为父级-> helper- >父->助手->父->等等...

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

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的属性中。

虽然有一些方法可以解决

我对代码进行了一些调整,在console.loging结果之后,它看起来更加干净。 我将其发布为可能的答案,因为,我可以编辑我的问题,但是我希望将反馈与问题分开,并查看除已发布的内容之外,是否有人有其他可能的更改或替代方法,可能会提供更好的解决方案。

现在,我将继续:

var Parent = function(identity) {
    if (identity) {
        this.identity = identity;
        this.group = $(this.identity);
        if (this.group.length > 0) {
            this.elems = new Array();
            this.helper = new Helper(this);
            this._setup(true);
        }
    }
    return this;
};

var Helper = function(reference) {
    for (var key in reference) {
        if (!this[key]) {
            this[key] = reference[key];
        }
    }
};

并据此从那里延伸。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM