Merge objects using $.extend() in jQuery

Have you ever come across a requirement in which you need merge many objects in one object? Okay let me clarify question in simpler words. Assume you have two objects as given below. object1 is defined as below,


var object1 = {
 red: 0,
 blue: { lightblue: 24, darkblue: 12 },
 black: 17
 };

And another object is object2.


var object2 = {
 white: 200,
 blue: {lightblue:40}
 };

Let us say you have to merge object2 in object1. Here merge means merging properties of object2 in object1. You can do this in jQuery using extend() function.


$.extend(object1, object2);
 console.log(object1);

 

Let us say you have to merge object2 in object1. Here merge means merging properties of object2 in object1. You can do this in jQuery using extend() function.

Now if you go ahead and view console you see following output. As you can see value for blue property in object1 has been changed with the value of object2’s blue property.

image

This is the way $.bind() merge two objects in jQuery. There could be another scenario in which you want to merge objects recursively. Recursively means property value which is unique in target object will persist. For recursive binding you need to set first parameter as True.

 $.extend(true,object1, object2);
 console.log(object1);

In output you can see that now blue property of object1 has darkblue and lightblue both. Value of darkblue has been modified with object2 property value.

image

You can merge more than two objects as below and always remember that $.bind returns target object as output,


var object1 = {
 red: 0,
 blue: { lightblue: 24, darkblue: 12 },
 black: 17
 };
 var object2 = {
 white: 200,
 blue: { lightblue: 40 }
 };

 
 var object3 =
 {
 yellow: 234
 };
 var targetresult = $.extend({}, object1, object2, object3);
 console.log(targetresult);

 

In this way you can merge objects in JavaScript using jQuery $.bind() function. I hope you find this post useful. Thanks for reading.

Revealing Module Pattern in JavaScript

We talked about Prototype Pattern in previous posts. You can read them at below link.

Understanding Prototype Pattern in JavaScript

Understanding Prototype Pattern in JavaScript: Part # 2

Revealing Module Pattern allows us to achieve

  • Singleton object
  • Private Public behaviour of functions and properties in the object.

Let us consider the usual code we write. We also known as that functional spaghetti code.


var basicSalary;
 var salary;
 function CalculateSalaray(basicSalary) {
 salary = basicSalary * 10;
 }
 function PrintSalaray() {
 alert("Salary is " + salary);
 }

CalculateSalaray(200);
 PrintSalaray();

There is nothing wrong in above code snippet. However,

  • It is hard to maintain when functionality grows
  • It is hard to debug
  • It is hard to test

In Revealing Module pattern we put all code inside a function represented by a variable. This is self-executed function.

image

Revealing module pattern allows us

  • To achieve public private members
  • To make code more readable

In this pattern we put all functions and variable inside the object. In above case everything would be encapsulated inside salary object. To make anything public we need to make them part of return statement.


var salaray = function () {

//Private
 var sal;
 function calculateSal(basesal) {
 sal = basesal*1000;
 }

function printSal(basesal) {
 calculateSal(basesal);
 console.log(sal);

 }

 //Public

return {
 PrintSalary: printSal

 };

}();

salaray.PrintSalary(2000);

 

In above code snippet we have two private functions. One of private function is exposed at public in return statement. Since object is wrapped as self-executable function hence it works as singleton. We can call public functions on object itself.

If we want to remove singleton then two steps need to be followed,

  • Remove self-executable code
  • Create new object using new operator.

So above object salary can be modified as below. Now it will have private public property but it would not act as singleton


var salaray = function () {

//Private
 var sal;
 function calculateSal(basesal) {
 sal = basesal*1000;
 }

function printSal(basesal) {
 calculateSal(basesal);
 console.log(sal);

 }

 //Public

return {
 PrintSalary: printSal

 };

};

var mysal = new salaray();
 mysal.PrintSalary(789);
 var mysal1 = new salaray();
 mysal.PrintSalary(100);

 

In above code salary object is not a singleton and having private and public functions. In many terms Revealing Module pattern can be considered as one of the best JavaScript pattern. Three advantages of using Revealing Module Pattern are as follows,

  1. Achieve Singleton
  2. Get Private –Public method behaviour
  3. Better readability of code

I hope you find this post useful. Thanks for reading.

Understanding Prototype Pattern in JavaScript: Part # 2

Recently we had a look on Understanding Prototype Pattern in JavaScript. I tried to explain this pattern in most simplified way. In this post we will get more dipper and see how prototype works in JavaScript.

Putting it in simple words in prototype pattern, we create object using template of an existing object. In prototype pattern we create an object known as prototype. This object acts as prototype for any object created using this prototype.

For example, if we have an object named Salary with property basicSalary then all the objects created using object Salary as prototype will have basicSalary as property.

Let us try to understand it with an example. Consider you have a prototype object Salary as below,


var Salary =
 {
 basicSalary: 10000,
 printSalary : function()
 {
 console.log(this.basicSalary);
 }

};

 

var emp1Salary = Object.create(Salary);
 emp1Salary.basicSalary = 9000;
 emp1Salary.printSalary();

We have created Salary object as prototype and then created another object emp1Salary using Salary as prototype. Now emp1Salary also have basicSalary and printSalary as property. You can infer from result that using prototype inheritance is very easily achieved. In emp1Salary we are altering value of basicSalary property and as output you will get 9000 printed.

Other way Object.create() can be used by passing extra properties for derived objects. So for example if we want to have an extra property like bonus then that can be passed as second parameter. This can be done as follows

 var Salary =
 {
 basicSalary: 10000,
 printSalary : function()
 {
 console.log(this.basicSalary);
 }

};

var emp1Salary = Object.create(Salary, {"bonus":{value:1000}});
 // emp1Salary.basicSalary = 9000;
 console.log(emp1Salary.bonus);

In above example we have passed extra property bonus to object emp1Salary. Now emp1Salary has one extra property bonus.

If required we can work with prototype pattern without using Object.Create(). In below we are first creating salaryPrototype and then in a function we are using the prototype object and then creating emp1Salary using Salary as prototype.

 var salaryPrototype =
 {
 init: function (basicSalary) {
 this.basicSalary = basicSalary
 },
 printSalary: function () {
 console.log(this.basicSalary);
 }

}

 function salary(basicSalary)
 {

function F() { };
 F.prototype = salaryPrototype;
 var f = new F();
 f.init(basicSalary);
 return f;

}

var emp1Salary = salary("1898");
 emp1Salary.printSalary();

By using prototype we can achieve inheritance and since its always keep one instance of properties for all objects then it has good performance as well. I hope you find this post useful. Thanks for reading.

Understanding Prototype Pattern in JavaScript

I am writing this blog post from Bulgaria Sofia. I am here to attend Devreach conference organised by Telerik . In conference I had an opportunity to meet my great inspiration Dan Wahlin . I attended his session on “Patterns in JavaScript” and I must say it was one of the best technical session I have attended so far. He explained such a complex topic in the easiest manner to gathering of more than 150 people in the room. I was one of them and I had good learning.

You can watch his course on same topic “Structuring JavaScript Code” on PluralSight here

In this post I am trying to explain my understanding on Prototype Pattern in JavaScript after Dan session. I hope you will like this.

So, Let us start with a simple code to calculate and print salary. Usually we write code as given below to calculate and print salary


var basicSalary;
 var salary;
 function CalculateSalaray(basicSalary) {
 salary = basicSalary * 10;
 }
 function PrintSalaray() {
 alert("Salary is " + salary);
 }

CalculateSalaray(200);
 PrintSalaray();

Everything is good about this code but,

  • It is hard to maintain when functionality grows
  • It is hard to debug
  • It is hard to test

Entire code is at the same place so if later a modification is required that has to be done in code itself. Let us consider an example that formula to calculate salary has been changed then that change has to be incorporated in the code. Alter or override of any function has to be done in existing code and that can lead to many unexpected bug in application. As a developer you need to modify CalculateSalary() function in the existing code and that may break many other things.

Let us try to achieve above requirement using Prototype Pattern. We will write above code adhering to Prototype Pattern.


var Salary = function(basicSalary)
 {
 this.basicSalary = basicSalary;
 var salary;
 };

Salary.prototype =
 {
 calculateSalaray: function () {
 this.salary = this.basicSalary * 10;
 },
 printSalaray: function () {
 alert(this.salary)
 }

};



var sal1 = new Salary(100);
 var sal2 = new Salary(200);
 sal1.calculateSalaray();
 sal1.printSalaray();
 sal2.calculateSalaray();
 sal2.printSalaray();

There are couple of advantage of code following Prototype pattern over code we written in first example,

  • Code is reusable
  • Functions can be override through prototyping
  • There is no variable or functions in global namespace

Biggest example is functions are loaded into memory only once. Now again go back to one of the biggest problem in above example was overriding. We had to modify existing code to override or alter any functionality. In Prototype pattern if you want to modify or override any function you can do that easily either in same script file or separate script file as below,


Salary.prototype.calculateSalaray = function () {
 this.salary = this.basicSalary * 100;
 }

So as we see it is very easy in Prototype pattern to override any function and avoid global declaration of variable and function. Implementing Prototype pattern is also easy.

I hope now you have basic understanding of Prototype pattern in JavaScript. Thanks for reading and once again thanks to Dan Wahlin .