jQuery对象的新实例

时间:2014-04-02 11:15:05

标签: javascript jquery class oop object

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

(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“插件”来实现,但我不喜欢它用于Object / Class的这种情况。

有人可以帮助我吗?

谢谢

1 个答案:

答案 0 :(得分:0)

问题是因为原型层次结构中有一个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