Computer >> Computer tutorials >  >> Programming >> Javascript

How to invoke a function with a function constructor in JavaScript?


We can invoke a function in 3 ways. The first one is as a function, the second one is as a method and the third one is as a function constructor. But in all the three, invoking a function with a function constructor is a peculiar one because this method uses inheritance property. Actually, a constructor invocation creates a new object. The new object inherits the properties and methods from its constructor. There is no inheritance in the first 2 methods. 

Example

In the following example, initially, a function and a function constructor were created. The function constructor has inherited the properties from the function. So even though only values were given to it,  properties also executed as shown in the output. 

<html>
<body>
   <script>
      function myArg(arg1, arg2) {
         this.radius = arg1;
         this.height = arg2;
      }
      var x = new myArg(1,2)
      document.write(JSON.stringify(x));
   </script>
</body>
</html>

Output

{"radius":1,"height":2}