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

Add a property to a JavaScript object constructor?


Adding a property to an object constructor is different from adding a property to a normal object. If we want to add a property we have to add it in the constructor itself rather than outside the constructor whereas we can add anywhere in a normal object.

Example-1

In the following example, a property is added as it is in the case of a normal object. Since here we have used an object constructor, we have to add the property inside the constructor if not undefined will be executed as the output as shown below.

<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;
   }
   Business.language = "chinese";
   var person1 = new Business("Trump", "$28.05billion", "73", "President");
   var person2 = new Business("Jackma", "$35.6 billion", "54", "entrepeneur");
   document.write(person2.language);
</script>
</body>
</html>

Output

undefined

Example-2

In the following example, the property "language" is declared inside the constructor, therefore, we will get a normal result, unlike false values.

<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;
      this.language = "chinese";
   }
var person1 = new Business("Trump", "$28.05billion", "73", "President");
var person2 = new Business("Jackma", "$35.6 billion", "54", "entrepeneur");
document.write(person2.language);
</script>
</body>
</html>

Output

chinese