Read full post on falafel blog

Before we can understand prototypical inheritance, let us start with a problem statement. You have a student for whom you need to:

  • Calculate their grade
  • Print the grade

In JavaScript this can be simply implemented as follows:


var studentMarks;
var studentGrade;

function FindGrade(studentMarks) {
    if (studentMarks >= 80) {
        studentGrade = "A";
    }
    else {
        studentGrade = "B";
    }
}

function PrintGrade() {
    console.log("Student Grade is " + studentGrade);
}

FindGrade(60);
PrintGrade();

There are some inherent problems in the above approach:

  • Variables are defined globally
  • Code maintenance is tough as the functionality grows
  • Code debugging is tough
  • Code testing is tough

The major problem in the above code is that neither the PrintGrade nor the FindGrade functions are reusable. Any future requirements in the find grade logic or in the print logic will require a change in the existing code, and that may introduce new bugs and require testing again. As a developer we may not want this.

Let us go ahead and refactor above code as follows:

Read full post on falafel blog

Advertisements

One thought on “Prototypical inheritance in JavaScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s