為什麼需要合并兩個元件的屬性?因為開發元件時,使用者以json object形式傳遞參數進來,你準備開放10個參數,但是使用者可能只傳遞了5個,你的代碼如果去訪問其餘5個屬性,就會出現notdefined錯誤,你不可能在內部一一去判斷某個屬性是否定義。為了省事,就定義一個預設的參數元件,然後和使用者傳入的參數元件合并。
比如:
//定義元件=======================yjCurveDefaultOption = { rawData: null, renderTo: "", xAxisTitle: "", xAxisUnit: "", yAxisTitle: "", yAxisUnit: "", chartTitle: "", xAxisIsDatetime: false}yjCurve = function (option) { //合并使用者給的參數和預設參數,如果不合并,後面可能訪問到沒有定義的屬性報錯 option = $.extend({}, yjCurveDefaultOption, option); build(); function build() { }}
//使用元件========================var rawData1 = [[2.5, 12907]];var c1 = new yjCurve({ xAxisIsDatetime: false, rawData: rawData1, xAxisTitle: "ShotCount", renderTo: "Div1", chartTitle: "Mold Temperature", yAxisTitle: "Temperature", yAxisUnit: "℃"});
如何合并兩個元件的屬性, 這裡有詳細討論:
http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically
jquery本身有提供這樣的函數:
// merge options object into settings objectvar settings = { validate: false, limit: 5, name: "foo" };var options = { validate: true, name: "bar" };jQuery.extend(settings, options);// now the content of settings object is the following:// { validate: true, limit: 5, name: "bar" }var defaults = { validate: false, limit: 5, name: "foo" };var options = { validate: true, name: "bar" };/* merge defaults and options, without modifying defaults */var settings = $.extend({}, defaults, options);// the content of settings variable is now the following:// {validate: true, limit: 5, name: "bar"}// defaults and options variable remained the same
hightcharts.src.js裡面的函數:
function merge() { var i,len = arguments.length,ret = {},doCopy = function (copy, original) {var value, key;for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]'&& typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } }}return copy;}; // For each argument, extend the return for (i = 0; i < len; i++) { ret = doCopy(ret, arguments[i]); } return ret;}