Two Problems of a JavaScript Class

 

Starting ECMA 6, JavaScript has class keyword to create a class. I have written in detail about class here. There is no second question that class simplifies the way object is created, inheritance is implemented etc. JavaScript class has,

  • Constructors
  • Methods
  • Extends etc.

Above features of a class helps to easily write Object Oriented JavaScript. As a developer, you do not need to know complexities of prototype chains, relationship between function constructor and its prototype object, and value of object’s __proto__ properties etc. to write effective Object Oriented JavaScript.  So, class keyword  is good addition to JavaScript language, however it is not gospel perfect. It has some problems, which may restrict you to write full-fledged Object Oriented JavaScript. In this post, I am going to share two such problems. Read along,

No Static Member Properties in class

A static member property is shared by all object instance of the class. JavaScript class does not allow creating it inside the class.

You cannot declare properties directly in the class. You can only have it through class’s constructors, and properties created inside constructor is local to the object instances and not shared by all of them.

Above code will throw error “unexpected identifier”.  There is a work around to create static property using the class prototype.

Now on the instances of Speaker class, you can access static property count.

Therefore, you are able to create a static property, but not without help of understanding of prototype.  In my opinion class should have a way to create static property directly inside the class like a method or constructor.

Object instances does not copy definitions from class

To understand this problem, let us first revise Constructor Invocation Pattern and prototype chain. You have a function constructor Speaker.

Using new operator, you can create object instances,

In this approach, a and b object instances both have their own copy of hello method.  Now if you add a hello method to Speaker.prototype, still a and b object instances will access their own copy of hello method. Consider below code:

Read full article on the Infragistics blog

How to add a static member property in a JavaScript class?

Recently while solving a problem, I came across a requirement to create a property in a JavaScript class, which needs to be shared by all the object instances. In the programming world, these types of properties are called Static Properties.

There are various scenarios when you need a static member property:

  • When counting number of object instances created from a particular class
  • When logging some information at the class level instead of object instance level, etc.

To create a static property, you should know two important things:

  1. A JavaScript class cannot have a member property. You can only create it using a constructor
  2. Like the function constructor, a JavaScript class also has a prototype

Well, if you are a champion of prototypes, you must have guessed the answer in your mind by this time.  Any way, let us move forward to see the implementation,

Read full article on the Infragistics blog

How to Create Basic Inheritance in JavaScript Constructors

There are four ways to create an object in JavaScript. They are as follows:

  1. Object as literal
  2. Constructor Invocation Pattern
  3. Object.create() method
  4. Using class after ES6

Implementation of Inheritance varies according to the object creation method. In this post, I am going to explain creating inheritance in between a function constructor.

Let’s say you have a function:

If you call the animal function using new operator, an object will be created. This way of object creation is also known as “Constructor Invocation Pattern

Object dog and cat both have their own names and age properties. If you want a property or method to be shared across all objects, add that to the prototype of the function.

Using the JavaScript prototype chain, both dog and cat objects can access the canRun method.

Next, let us create another constructor – human:

At this point in time, human and animal functions do not have any relationship. However, we know that human is also an animal. There are two problems with the human constructor.

  1. It has duplicate codes for name and age initialization. It should use animal constructor for this purpose.
  2. It does not have any link with animal constructor

The above said two problems can be removed by creating inheritance in between animal and human function constructors.

You can solve problem 1 of code duplication by modifying the human function as below:

Now, in human function, we are using the call method to manually pass a current object as a value of ‘this’ in animal function. This approach is also called Indirect Invocation Pattern. Now, an object instance for human can be created as shown below:

So far, we have solved problem 1 of code duplication; however, human function is still not linked to animal function. If you try to call canRun method on h1 object, JavaScript will throw you an error.

You can fix this problem by linking the prototype of the human function with the prototype of the animal function constructor. There are two ways to do that.

  1. Using __proto__
  2. Using Object.create() method

You can link prototype of function constructors using Object.create() as shown below:

You can link prototype of function constructors using __proto__ as shown below:

I would prefer the Object.create() method because__proto__ may not be supported in many browsers. After linking prototypes, in one way, you have created inheritance in between animal and human function constructors. Object instance of human can read all properties of animal function and can execute animal function methods.

Read full article on the Infragistics blog here

How to seal, freeze and prevent extension of an object in JavaScript

Read full article on the Infragistics blog

In modern JavaScript, objects are integral, and having a strong understanding of topics surrounding objects is necessary for writing better JavaScript. You can create an object in four ways in JavaScript.

Read about them in greater detail here.

Once you know how to create an object, you may wish to learn about object property descriptors. As a recap, let us say you have an object –cat:

Each object property contains more information than just a value. For example, you can print other property information using the Object.getOwnPropertyDescriptor method

On the console, you can see that a property name offers further information:

image

As is very clear, if writable is set to true, you can rewrite a property value, etc. You can read more about the JavaScript Object Property Descriptor here.

As of now, you know about object property descriptors, so if you are required to make a property Read-Only, you will set the property writable to false.

Next, let us go through a few more requirements for changing the default behavior of a JavaScript object.

  1. Prevent an object from having new property
  2. In addition to requirement 1, mark all properties configurable to false
  3. In addition to requirement 2, make all properties writable to false

Starting with ECMA 6, you have methods to achieve the above requirements. Let us take them one by one:

Object.preventExtensions

Let us say, you have an object – cat:

With Default behavior, you can add properties to a JavaScript object. Thus, the below operation is possible:

To prevent the default behavior from adding properties dynamically in an object, you need to use Object.preventExtensions(). This method prevents an object from having new properties added to it.

After using Object.preventExtensions on the object, if you add new property color, JavaScript will ignore it, and as an output you will get undefined.

If JavaScript is in strict mode, you will get an error if you add a new property to an object that is not extensible.

In strict mode, you will get an error with very clear messaging that states, “cannot add property, object is not extensible”

image

To summarize, you should use the object.preventExtensions method to prevent an object from having new properties added to it.

Read full article on the Infragistics blog

Module Pattern in JavaScript

In JavaScript, code encapsulation can be achieved using Modules Patterns. In addition, it is used to create private and public properties. There are various ways a module pattern can be implemented. In this article, we will learn to create a module pattern in ES5. Before we go ahead and start looking into implementation of the module pattern, here are some of the benefits:

  • Freeze the scoping
  • Code encapsulation
  • Creating private or public scope
  • Creating a namespace
  • Creating public and private encapsulation

We can implement a module pattern using JavaScript Object Literals and Immediately- Invoked function expression. Just to refresh your memory, an object literal will look like the below listing:

You can add properties after creation of object. Also, an Immediately- Invoked function expression looks like the example below:

With combination of these two, we can implement Module Patterns in JavaScript. Let us start with creating the module:

It is a self-contained module or an anonymous closure. It creates the scope for the function and everything is wrapped inside that function itself. So, when we tried to access price outside the function, it was undefined. Keep in mind that this anonymous module is present in the global scope.We can export the module by assigning it to a variable using expression, and then creating private and public encapsulation using the return statement. Consider below code:

We are doing following in above code snippet,

  1. Creating an IIFE.
  2. Assigning IIFE function to a variable
  3. Returning an anonymous object literal to create private and public encapsulation.

All properties of returned object would become public and can be accessed outside the module, however, any variable not part of the returned object cannot be accessed outside module. That is why for price we are getting 800 as the output, but, for color, value is undefined because it is private to the module1. Let us modify module1 to have more private and public properties, as shown in the listing below:

Read full article on the Infragistics blog

20 JavaScript articles to brush up your JavaScript language

I have been evangelist of JavaScript and Angular for some time now. Below, I am consolidating 20 JavaScript articles written by me. These articles will help you in understanding basic language construct of JavaScript. Topics like objects, hoisting, functions etc. are covered in these articles. Let me know how you find them.

clip_image002

1. How to Count the Number of Properties of the JavaScript Object

https://www.infragistics.com/community/blogs/b/infragistics/posts/how-to-count-the-number-of-properties-of-the-javascript-object

2. Four Ways to Create Objects in JavaScript https://www.infragistics.com/community/blogs/b/infragistics/posts/easy-javascript-part-13-four-ways-to-create-objects-in-javascript

3. What are the Call and Apply Methods? https://www.infragistics.com/community/blogs/b/infragistics/posts/easy-javascript-part-12-what-are-the-call-and-apply-methods

4. Simplifying function expressions and the function statement https://www.infragistics.com/community/blogs/b/infragistics/posts/easy-javascript-part-11-simplifying-function-expressions-and-the-function-statement

5. Class in JavaScript

https://www.infragistics.com/community/blogs/b/infragistics/posts/easy-javascript-part-10-class-in-javascript

6. What are Template Literals?

https://www.infragistics.com/community/blogs/b/infragistics/posts/easy-javascript-part-9-what-are-template-literals

7. What are getters and setters?

https://www.infragistics.com/community/blogs/b/infragistics/posts/easy-javascript-part-8-what-are-getters-and-setters

8. Arrow functions in JavaScript https://www.infragistics.com/community/blogs/b/infragistics/posts/easy-javascript-part-6-arrow-functions-in-javascript

9. Simplifying function hoisting

https://www.infragistics.com/community/blogs/b/infragistics/posts/easy-javascript-part-5-simplifying-function-hoisting

10. What is the arguments object in a function

https://www.infragistics.com/community/blogs/b/infragistics/posts/easy-javascript-part-4-what-is-the-arguments-object-in-a-function

11. What is a Default Parameter in a Function?

https://www.infragistics.com/community/blogs/b/infragistics/posts/easy-javascript-part-3-what-is-a-default-parameter-in-a-function

12. Learn the “let” Statement

https://www.infragistics.com/community/blogs/b/infragistics/posts/easy-javascript-part-1-_2d00_-learn-the-let-statement

13. How to create constants in JavaScript?

https://www.infragistics.com/community/blogs/b/dhananjay_kumar/posts/how-to-create-constants-in-javascript

14. How to print or enumerate properties of a JavaScript object?

https://www.infragistics.com/community/blogs/b/dhananjay_kumar/posts/how-to-print-or-enumerate-properties-of-a-javascript-object

15. How to locate a particular object in a JavaScript Array

https://www.infragistics.com/community/blogs/b/dhananjay_kumar/posts/how-to-locate-a-particular-object-in-a-javascript-array

16. What are Closures in JavaScript?

https://www.infragistics.com/community/blogs/b/dhananjay_kumar/posts/what-are-closures-in-javascript

17. Simplifying Objects, Inheritance and prototype in JavaScript

https://www.infragistics.com/community/blogs/b/dhananjay_kumar/posts/simplifying-objects-inheritance-and-prototype-in-javascript

18. 11 Things About JavaScript Functions that .NET Developers Should Know: Part 1

https://www.infragistics.com/community/blogs/b/dhananjay_kumar/posts/all-about-javascript-functions

19. 11 things about JavaScript functions that .NET developers should know: Part 2

https://www.infragistics.com/community/blogs/b/dhananjay_kumar/posts/11-things-about-javascript-functions-that-net-developers-should-know-part-2

20. Objects in JavaScript for .NET developers

https://www.infragistics.com/community/blogs/b/dhananjay_kumar/posts/objects-in-javascript-for-net-developers-part-1

I hope these two articles will help you in getting along with JavaScript. Have comment or feedback tweet me at @debug_mode.

How to Count the Number of Properties of the JavaScript Object

While working with JavaScript, I come across a requirement to count a number of properties in a JavaScript object.  I found two ways to find the number of properties in an object. They are as follows:

  1. Using for loop
  2. Using Object.keys

Consider an object, “cat”, as demonstrated below:

You can find a number of properties by iterating in a for loop and update counter, as shown in the below listing:

Above code will print “2” as output.

The above approach not only prints the object’s own enumerable properties, but it also prints properties of objects to chich it is linked.  To further understand it, let us consider listing:

There are two objects, cat and animal, and the cat object is linked to an animal object using __proto__ property.  Now, when you use for loop to iterate and count a number of properties, it will also count enumerable properties of the animal object. Therefore, the code listing below will print “3”.

Read full article on the Infragistics blog

Class in JavaScript

Read full article on the Infragistics blog

ECMAScript 6 introduced the class keyword to create classes in JavaScript. Now, you can just use the class attribute to create a class in JavaScript. Before ECMA 6, whenever you called a function using a new operator, the function returned a new object. Therefore, the function was acting as a class and known as a constructor. This way of calling a function to return an object is also known as the Constructor Invocation Pattern.

But In ECMAScript 6, a class can be created using the class keyword. Consider the code below:

In the above code snippet, you have created a class named Car using the ECMAScript 6 classkeyword. You can also create an object of the Car class as shown below:

The JavaScript class is a simplified syntax for the usual prototype based inheritance. It does not offer any new way of object creation or prototype inheritance and does not bring any new models of object orientation or inheritance in JavaScript. You could say that a class is a special function to create objects.

Read full article on the Infragistics blog

Simplifying function expressions and the function statement in JavaScript

Read full article on the Infragistics blog

In JavaScript, a function can be created in three possible ways:

  1. Function as an expression
  2. Function as a statement
  3. Arrow functions

In this post, we will learn about function expressions and the function statement.

Consider the following code:

When you create a function as shown above, it is called a function declaration or statement. You can rewrite the code above to add a function in different ways, as shown below:

The function created above is called a function expression – in this case, an anonymous function expression. A named function expression can be created as below:

The name of the function expression can only be used inside a function body, which is helpful in recursion. A function expression can either be a:

  1. Named function expression
  2. Anonymous function expression

The third method of creating a function is by using the Arrow function, which was introduced in ECMAScript 6. You can learn more about Arrow functions here.

Read full article on the Infragistics blog

What are the Call and Apply Methods in JavaScript

Read full article on the Infragistics blog

In JavaScript, the apply() and call() methods execute a function in the context (scope) of the first argument you pass to them. Let’s take a look at them in action to learn more. Say that you have an object person as shown below:

And in addition, you have a function message as shown below:

Now, you have a requirement to pass the person object as the value of this in the function. In addition to explicitly passing the value of this, you also need to pass the value for the age parameter.

You can pass the context (the value of this) explicitly using by either the call() or apply() methods. Consider the following code:

Using the call method, we are passing the object person as the value of this inside message function.  You can achieve the same using the apply() method as shown in the listing below:

In JavaScript, the call() and apply() methods work in almost exactly the same way, but with a few key differences:

  1. The first parameter of both call() and apply() is the value of this object.
  2. In the call() method, the other arguments to function will be passed as separate comma separated values.
  3. The call() method takes zero or more individual parameters.
  4. In the apply() method, the second parameter is an array.
  5. The apply() method takes an array of parameter.
  6. You should use the call() method when the number of function parameters is fixed.
  7. You should use the apply() method, when the number of function parameters is not fixed.

 

Read full article on the Infragistics blog