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.

No comments:

Post a Comment