

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Add a method to a JavaScript object constructor?
- How to add a property, method to a JavaScript constructor?
- JavaScript Boolean constructor Property
- JavaScript Date constructor Property
- How to add a method to a JavaScript object?
- What is a constructor to create String object in JavaScript?
- How to remove a property from a JavaScript object?
- How to add an element to a javascript object?
- How to create JavaScript objects using object() constructor?
- How to add 30 minutes to a JavaScript Date object?
- How to add 2 hours to a JavaScript Date object?
- How to add 10 seconds to a JavaScript date object?
- How do we remove a property from a JavaScript object? - JavaScript
- Removing property from a JSON object in JavaScript
- How do I remove a property from a JavaScript object?
Advertisements