Thursday, September 5, 2019

Prototype in JavaScript


In this post, we will discuss what are prototypes in JavaScript, how they help JavaScript in achieving the concepts of Object Oriented Programming.

JavaScript is a very dynamic programming and it allows to add new properties or function on object at any time.

Adding new property by using Prototype

Here is an example of adding new property by using Prototype

<script type="text/javascript">
    class Person {
        constructor(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;         
        }

        name() {
            return this.firstName + ' ' + this.lastName;
        }
    };

   _person = new Person("Henry", "Ford");
   _person.Age = 18;

    console.log(_person.name());
    console.log(_person.Age);
</script>

Output :

Henry Ford
18

By using Prototype, we can define new property Age of Person object.

Adding new function by using Prototype:

Here is an example of adding new function by using Prototype

<script type="text/javascript">
    class Person {
        constructor(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;         
        }

        name() {
            return this.firstName + ' ' + this.lastName;
        }
    };


   _person = new Person("Henry", "Ford");
   _person.hello = function () { return "Hi I am " + this.firstName + ' ' + this.lastName; }
  
    console.log(_person.hello());

</script>

Output:

Hi I am Henry Ford

By using Prototype, we can define new function ‘hello’ method of Person object.


No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...