Tuesday, 11 March 2014

jQuery.extend() example



Welcome to my journey of extending objects in JavaScript frameworks; let’s explore jQuery! Extending an object in jQuery is simple, there are just a few rules you need to understand.
Extension works from left to right and you’re allowed to pass as many objects to the function as you want.
Whatever is passed to the $.extend argument last wins.
For instance:
var start = {
    id: 123,
    count: 41,
    desc: 'this is information',
    title: 'Base Object',
    tag: 'uncategorized',
    values: [1, 1, 2, 3, 5, 8, 13]
};

var more = {
    name: 'Los Techies',
    tag: 'javascript'
};

var extra = {
    count: 42,
    title: null,
    desc: undefined,
    values: [1, 3, 6, 10]
};

var extended = $.extend(start, more, extra);

Output:
{
    "id": 123,
    "count": 42,
    "desc": "this is information",
    "title": null,
    "tag": "javascript",
    "values": [1, 3, 6, 10],
    "name": "Los Techies"
}

Note: undefined data will not extend.


No comments:

Post a Comment