TIL jQuery extend function

Today I learned about jQuery extend function. It is quite simple to use and as useful as it is simple!

What it does? Simply merges one object into another, adding properties from other objects to our target. For example:

	var targetObject = {
		propertyA: "string1",
		propertyB: 12.3
	};

	var mergeObject = {
		propertyA: "overrideString",
		propertyC: new Date()
	}

	$.extend(targetObject, mergeObject);
	console.log(targetObject);

What we get in result is:

	object { propertyA: "overrideString", propertyB: 12.3, propertyC: Fri Feb 26 2016 18:03:47 GMT+0100 }

So merged object, with last win rule – the same property name will overwrite previous values in source objects. Or in fact in previous merge objects since you can pass multiple merge objects there.

What it is used for? Well, jQuery itself uses it to extend jQuery functionality. Wrote some jQuery plugin? you can $.extend(myPluginObject) and it will merge your object into jQuery (if there is only one param, jQuery is assumed as target). Why I find it useful? When initializing javascript structure, we often provide it with init data, however we want some of it to be taken from default if user did not provide overrides. That is easily done now:

	var actualConfig = $.extend({}, defaults, initData);

It will return new object, copying first values from our defaults and then overriding them with whatever user did provice in initData. Neat!

Advertisements

One thought on “TIL jQuery extend function

  1. Pingback: Object management in javascript; default values | Why u no code?!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s