Going Object with JavaScript

We have all been there, those random written variables and function that are good enough to do one simple task, but breaks often when used for more than one tasks, reason? well, it’s because the code is meant for just one purpose, this is where object oriented programing comes in to rescue.

Yes!, we can use functions for the purpose but what if we need somewhat similar code structure but with different values? (IE: inheritance), JavaScript with combination of object oriented programing makes JavaScript far more powerful.
for example:

alert("hello world");

This is plain code JavaScript to alert “hello world” in the browser, it seems fine enough for the purpose, this is exactly what most of the beginners do, but there’s a few problem, which will be explained later, for now look at the following code

function al(msg){ 

    alert(msg);
}

This is more friendly as compared with the alert(“hello world”), this allows us to change a string, if the purpose of the code is not complex, then this could be used.

here’s one more example

Operations={
  value:"i am doing fine...",
  al:function(val) { alert(val)},
  alval:function(){alert(this.value);}
}

now that we have converted this into an object, we can simply call it by using dots. (.)

for example:

alert(Operations.value); //Prints: i am doing fine...

Operations.al("hello world"); //Prints function's parameters 

Operations.value="my updated thing"; //Assigns "my updated thing" to value. 

Operations.alval; //will print the value which was updated....

now this object can be copied and modified as per needs.

Operations=NewOperations;

here, NewOperations could be used as Operations, which could be modified as per needs!

Pretty Simple right?

About the author

sarabpreet

A DevSigner, Minimal, building this for next million users, the Creative lad at Gult Design. (https://gult.design))

Add comment

By sarabpreet

Latest from Sarabpreet