Sunday, 29 May 2016

Adding Methods to our object in JavaScript

In JavaScript,  we can add methods to our object, which are mainly used by the web developers.

Let me clear this concept with an example.

methodstoObject.html:-

<html>
<head>
<script type="text/javascript">
    function people(name,age){
this.name = name;
this.age = age;
this.yearsUntilRetire = yearsLeft;
}

function yearsLeft(){
 var numYears = 65 - this.age;
 return numYears;
}

  var robertson = new people("Robertson Muddy", 28);
</script>
</head>
  <body>
   <script type="text/javascript">
      document.write("<b>" + robertson.yearsUntilRetire()+ "</b>");
   </script>
  </body>

</html>



Output:-


Description:-

           Here, people is the method declared within the script tag, along with name & age as the function parameters. "yearsLeft" is the method which is used in the people method, by declaring it to "yearsUntilRetire". So, to use it, we need to write as "robertson.yearsUntilRetire()", where "robertson" is the object declared before.

Object Initialization in JavaScript

JavaScript is one of the scripting language that is mainly used in web applications. "Object" is one of the good concept which is used while coding with javascript.

Let me explain it with a suitable example:-

objectinitial.html :-

<html>
<head>
<script type="text/javascript">
  ronny = {name:"Ronny Thomson", age:24};
  shilpa = {name:"Shilpa Thomson", age:20};
</script>
</head>
  <body>
   <script type="text/javascript">
     console.log(ronny.name + " loves " + shilpa.name + " as she is " + shilpa.age +" yrs old!");
   </script>
  </body>

</html>


Output:- 



Explanation:- 

             Here, "ronny" & "shilpa" are objects initialized with particular data. "name" is the key of the object "ronny" and "Ronny Thomson" is the value of it. So, to display the value of the key - name, we need to use dot(.) operator, i.e, ronny.name.