Print Shortlink

Dynamic access in JavaScript

A simple yet powerful feature in JavaScript that can save you several lines of code is the ability to dynamically access members of a class(or a function). A Calculator function is shown below

function Calculator(){
	this.add = function(num1,num2){
		return num1+num2;
	}
	this.subtract = function(num1,num2){
		return num1 - num2;
	}
}

Let’s create an instance of Calculator ‘calc’.

	var calc = new Calculator();

If you want to access the add and subtract methods based on the user input, you’ll land up having if-else conditions in the code like,

		
	if(someCondition)
		calc.add(num1,num2); //num1 and num2 are textbox inputs
	else
		calc.subtract(num1,num2);

The dynamic feature in JavaScript can come in handy in this situation. You can invoke the add and subtract methods like shown below.

	var operation = "add"; //or "subtract" based on the user input
	calc[operation](num1,num2); 

So the members of the object can be invoked using an array like syntax. This feature is very widely used in languages like Groovy also.
This spares us several lines of code in JavaScript.

Page 1 of 1

One Response

  1. Nitya

    Good one…couldn’t find time for every other post recently, but will catch up….keep posting :)

Leave a Reply