Javascript jQuery对象的新实例
我在创建对象的新实例时遇到了一个小问题Javascript jQuery对象的新实例,javascript,jquery,class,oop,object,Javascript,Jquery,Class,Oop,Object,我在创建对象的新实例时遇到了一个小问题 (function ($) { $.Graph = function (config) { jQuery.extend(true, self.options, config || {}); // do something return this; } $.Graph.prototype = { data: [], options: {...} } }(jQuery)); 问题是,如果我创建此对象的两个实例:
(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“plugin”来实现,但我不喜欢对象/类的这种情况
有人能帮我吗
谢谢问题在于,原型层次结构中有一个
选项
对象。您的代码每次都会修改共享对象,而不是为图形的每个实例创建一个新的选项对象
一种可能的解决方案是使用不同的默认选项对象,如
(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);
演示:试试什么是
self.options
?哦,对不起,应该是这个。options,我试过一些东西