javascript元件属性合并

来源:互联网 发布:添加打印机端口已存在 编辑:程序博客网 时间:2024/05/24 22:41

为什么需要合并两个元件的属性?因为开发元件时,用户以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;}