最近发现了$.extend并将其应用于我的代码:
var chartFactory = function(options) {
this.defaults = {
type: "line",
width: "800",
height: "500",
heightScale: {
domain: ["0", "250"],
range: ["300", "0"]
},
widthScale: {
domain: ["0", "250"],
range: ["0", "900"]
},
Yaxis: {
ticks: ["5"],
scale: "heightScale",
orient: "left"
},
Xaxis: {
ticks: ["10"],
scale: "widthScale",
orient: "bottom"
}
};
$.extend(this.options, options, this.defaults);
};我有一个chartFactory类,其中lineChart是它的一个对象。
编辑:试图将对象值的内容与默认值合并,以便保留已生成的新对象的值,并且结果应该在新对象上。
var lineChart = new chartFactory({
type: "line",
Xaxis: {
ticks: ["20"],
scale: "widthScale",
orient: "bottom"
}
});因此,基本上,当我安慰lineChart(console.log(lineChart) )时,出现了这样的情况:

lineChart.Xaxis.ticks应该是"20“。
我做错什么了?
发布于 2014-03-25 05:09:08
您必须首先创建this.options,然后将另外两个对象合并到该对象中,首先传递this.defaults,然后是options,因为后者将覆盖前者中的属性。
var chartFactory = function(options) {
this.defaults = {
type: "line",
width: "800",
height: "500",
heightScale: {
domain: ["0", "250"],
range: ["300", "0"]
},
widthScale: {
domain: ["0", "250"],
range: ["0", "900"]
},
Yaxis: {
ticks: ["5"],
scale: "heightScale",
orient: "left"
},
Xaxis: {
ticks: ["10"],
scale: "widthScale",
orient: "bottom"
}
};
this.options = {};
$.extend(this.options, this.defaults, options);
};
var lineChart = new chartFactory({
type: "line",
Xaxis: {
ticks: ["20"],
scale: "widthScale",
orient: "bottom"
}
});FIDDLE
发布于 2014-03-25 05:14:17
返回您创建的对象:
var chartFactory = function(options) {
/* define this.defaults */
return $.extend({}, this.defaults, options);
};发布于 2014-03-25 05:32:02
var settings = $.extend({
readonly : 'true', // true for static rating only and false for the clickable star.
score : '0', // total score of item
userscore : '0', // ratedby user
count : '', // rating count means no of user rated
size : 'medium', // size if star large or medium currently no option for small
click : function(){} /// default function for click
}, options);就像这样,您需要将值传递给{},
https://stackoverflow.com/questions/22625794
复制相似问题