【问题标题】:jQuery new instance of objectjQuery 新的对象实例
【发布时间】:2014-05-13 15:07:39
【问题描述】:

我在创建新的对象实例时遇到了一点问题。

(function ($) {
$.Graph = function (config) {
    jQuery.extend(true, self.options, config || {});

    // do something

    return this;

}

$.Graph.prototype = {
    data: [],
    options: {...}
}
}(jQuery));

问题是如果我创建这个对象的两个实例:

Graph1 = new $.Graph({'container': 'graph1',...});
Graph2 = new $.Graph({'container': 'graph2',...});

之后

console.log(Graph1.options.container);
console.log(Graph2.options.container);

我得到了他们两个结果'graph2'。我认为,第一个实例已被第二个实例覆盖。 请问我该怎么做。也许可以通过 jQuery“插件”来实现,但对于这种对象/类的情况,我不喜欢它。

有人可以帮我吗?

谢谢

【问题讨论】:

标签: javascript jquery class oop object


【解决方案1】:

问题在于原型层次结构中有一个option 对象,因此您的代码每次都会修改共享对象,而不是为每个 Graph 实例创建一个新的选项对象。

一种可能的解决方案是使用不同的默认选项对象,例如

(function ($) {
    $.Graph = function (config) {
        this.options = jQuery.extend(true, {}, $.Graph.defaultOptions, config || {});
        return this;
    }

    $.Graph.prototype = {
        data: []
    }
    $.Graph.defaultOptions = {
        container: '',
        some: 'other'
    }
}(jQuery));


Graph1 = new $.Graph({
    'container': 'graph1'
});
Graph2 = new $.Graph({
    'container': 'graph2'
});


console.log(Graph1, Graph1.options.container);
console.log(Graph2, Graph2.options.container);

演示:Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 2022-08-04
    • 1970-01-01
    相关资源
    最近更新 更多