Umesh Patil
Umesh Patil

Reputation: 10685

Uses of Extend Function in javascript

Below is the extend function in core javascript. It is same as $.extend() in jQuery. It is used to update/modify the JavaScript Object.

var extend= function() {
            var options,
            name,
            src,
            copy,
            copyIsArray,
            clone,
            target = arguments[0] || {},
            i = 1,
            length = arguments.length,
            deep = false;

            if (typeof target === "boolean") {
                deep = target;
                target = arguments[1] || {};
                i = 2;
            }

            if (typeof target !== "object" && !isFunction(target)) {
                target = {};
            }

            if (length === i) {
                target = this;
                --i;
            }

            for (; i < length; i++) {
                if ((options = arguments[i]) != null) {
                    for (name in options) {
                        src = target[name];
                        copy = options[name];

                        if (target === copy) {
                            continue;
                        }

                        if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
                            if (copyIsArray) {
                                copyIsArray = false;
                                clone = src && isArray(src) ? src: [];

                            } else {
                                clone = src && isPlainObject(src) ? src: {};
                            }

                            target[name] = extend(deep, clone, copy);

                        } else if (copy !== undefined) {
                            target[name] = copy;
                        }
                    }
                }
            }
            return target;
        }

It is called as below:

    extend(curConfig, newConfig);   

As it is the standard function used everywhere to modify the object with new one. I want to understand and analyze this function.

  1. As function definition doesn't show any parameter can be passed, but while using it takes any number of parameters. So, How this function behaves ?
  2. What are diffrent uses of this function. What are ways to call it ?
  3. If 5 object parameters passed to function, First param will be destination and remaining will be source. Right ? Are the objects overridden or copied if not present ?

Can anyone explain with example ( or if possible with jsfiddle demo) ?

Thanks in Advance !

Upvotes: 0

Views: 154

Answers (1)

Quentin
Quentin

Reputation: 943586

As function definition doesn't show any parameter can be passed, but while using it takes any number of parameters. So, How this function behaves ?

It uses the arguments object.

What are ways to call it ?

You pass it an object to extend and any number of objects to extend it with.

Upvotes: 1

Related Questions