最近发现$ .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”。
我做错了什么?
答案 0 :(得分:2)
首先必须实际创建this.options
,然后将其他两个对象合并到该对象中,首先传递this.defaults
,然后传递options
,因为后者将覆盖前者的属性< / p>
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"
}
});
答案 1 :(得分:1)
返回您创建的对象:
var chartFactory = function(options) {
/* define this.defaults */
return $.extend({}, this.defaults, options);
};
答案 2 :(得分:-1)
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);
就像这样,你需要将值传递给{},