Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Quick tip: How to get started quickly with OOP-like coding style in JavaScript?

DZone's Guide to

Quick tip: How to get started quickly with OOP-like coding style in JavaScript?

· Web Dev Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

Writing JavaScript code in OOP style is something which is actively promoted in the last few years...

How to get started quickly with simple and straight forward example? Look at this one:

var Hobbit = function(name){
   this.Name = name;
   var steps = 0;  
   this.Run = function(speed, distance){
      //hobbit running algorithm goes here
      while(steps < distance){ 
        console.log(steps); //for debugging purpose only
        steps+=speed;
      }
   }
}

//all members containing this keyword are public members. Therefore we have one property Name which is public, and function/method Run accepting two parameters speed and distance, which is also public. See the usage bellow. 

//implementation

var frodo = new Hobbit("Frodo");
console.log(frodo.Name); //prints "Frodo"

//you can call the Run function/method too

frodo.Run(10, 2000); //prints all the iterations inside 'while' with the current 'steps' value

...and yes, you can create new closed 'things' representations, instantiate one inside other and do entire way of OOP-like development. 

I'm sure this was pretty straight forward, simple and easy to understand.

Happy Coding!
Hajan



Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

Topics:

Published at DZone with permission of Hajan Selmani, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}