Create many JavaScript objects as the same type?


It is very easy to create a single object than to create multiple objects of the same type. To breach this hurdle, javascript has provided object constructor function. Using this function, initially, we have to create the type of the object and later on, we need to declare the properties of the object.

Example

In the following example, initially, we have declared the type of object that contains the "name", "property", "age", and "designation". Later on, using that type we have created two objects and the corresponding properties were displayed in the output based on our requirement.

Live Demo

<html>
<body>
<p id = "prop"></p>
<script>
   function Business(name, property, age, designation) {
      this.Name = name;
      this.prop = property;
      this.age = age;
      this.designation = designation;
   }
   var person1 = new Business("Trump", "$28.8b", "73", "President");
   var person2 = new Business("Jackma", "$35.6b", "54", "entrepeneur");
   document.write(
      "My inpiration is " + person1.Name + " and i want to be an " + person2.designation + ".");
</script>
</body>
</html>

Output

My inpiration is Trump and i want to be an entrepeneur.
raja
Published on 07-Aug-2019 13:43:52
Advertisements