over 9 years ago
prototype property in JavaScript: The prototype property gives us freedom to add the new property and method into the object at any time. This is the global property in JavaScript which can be called through any JavaScript object at any time.
Example of prototype property : Here I will show you how to use the prototype property with an example.
- <!DOCTYPE html>
- <html>
- <body>
- <p id="demo"></p>
- <button onclick="show()">click</button>
- <script>
- employee = function(name, age) {
- this.name=name;
- this.age=age;
- }
- employee.prototype.salary = 2000;
- employee.prototype.display = function(){alert(this.salary)};
- var emp = new employee("John", 26);
- document.getElementById("demo").innerHTML = emp.salary;
- function show(){
- emp.display();
- }
- </script>
- </body>
- </html>
- Output : 2000
<!DOCTYPE html> <html> <body> <p id="demo"></p> <button onclick="show()">click</button> <script> employee = function(name, age) { this.name=name; this.age=age; } employee.prototype.salary = 2000; employee.prototype.display = function(){alert(this.salary)}; var emp = new employee("John", 26); document.getElementById("demo").innerHTML = emp.salary; function show(){ emp.display(); } </script> </body> </html> Output : 2000
And when you click on the click button it will show you the alert message with salary display on it. In the above example you can see that I have added one property called salary and one method called display after creating the employee object.
Can you help out the community by solving one of the following Javascript problems?
Do activity (Answer, Blog) > Earn Rep Points > Improve Rank > Get more opportunities to work and get paid!
For more topics, questions and answers, please visit the Tech Q&A page.
0 Comment(s)