Tech Junkie Blog: JavaScript Classes and Prototype Methods

Thursday, August 16, 2018

JavaScript Classes and Prototype Methods

A JavaScript class is different than classes in other languages like C# or Java.  A class in JavaScript means that the objects inherit properties from the same prototype object.  It is defined by using the function to initialize and return a new object.

First thing we have to do define the prototype object by creating a function constructor that initializes and creates a new object.  Let's say we have a bank account first we will create a constructor that will create a new account object.  We then define the class methods by defining the prototype methods.  After we do that all the new objects that created will inherit those prototype methods. Like the code below.

        function Account(balance, type) {
            this.balance = balance;
            this.type = type;

        Account.prototype.deposit = function (d) {

            this.balance = this.balance + d;
            return this.balance;

        Account.prototype.withdrawal = function (w) {
            this.balance = this.balance - w;
            return this.balance;

        var a = new Account(100, "Checking");
        var bonus = 10;
        var fine = 20;

        console.log("Deposit " + bonus + " " + a.deposit(bonus));
        console.log("Withdrawal " + fine + " " +  a.withdrawal(fine))
        console.log("Account type " + a.type);

The code above defines an account class using a function, and then we define the methods or behavior of the class with prototype methods.  After we opened the account we got a bonus of ten      dollars.  So we call the deposit the ten dollars to the account by calling the method deposit that belongs to the prototype of the class, which we inherit when we create the account object.

Our new balance is 110 dollars.  As you can see we set the objects property to the new balance.  When we pay the fine we subtract twenty dollars from the new balance.  All of this happens within the account object because we defined and initialized the account object with a constructor and use prototype methods.  We can create other objects with the same properties and behaviors by using the account class.  JavaScript does not have a class, but it can simulate classes with prototypes and functions.

No comments:

Post a Comment