Skip to content

Instantly share code, notes, and snippets.

@mohsen1

mohsen1/classical.md

Last active Dec 14, 2015
Embed
What would you like to do?
Classical Inheritance in JavaScript which never uses prototype object. This is bad code. It's here to demonstrate how bad Classical Inheritance is!

Let me introduce you to Classical Inheritance that never uses prototype. This is a bad coding exercise but will teach you the real Classical Inheritance which always compared to prototypal inheritance:

Make a custructor:

function Person(name, age){
  this.name = name;
  this.age = age;
  this.sayHello = function(){return "Hello! this is " + this.name;}
}

Make another cunstructor that inherits from it:

function Student(name, age, grade){
  Person.apply(this, [name, age]);
  this.grade = grade
}

Very simple! Student calls(applies) Person on itself with name and age arguments takes care of grade arguments by itself.

Now lets make an instance of Student.

var pete = new Student('Pete', 7, 1);

Out pete object will now contain name, age, grade and sayHello properties. It owns all those properties. They are not uplinked to Person through prototype. If we change Person to this:

function Person(name, age){
  this.name = name;
  this.age = age;
  this.sayHello = function(){
    return "Hello! this is " + this.name + ". I am " this.age + " years old";
  }
}

pete will no recieve the update. If we call pete.sayHello, ti will return Hello! this is pete. It will not get the new update.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment