In Douglas Crockford\'s JavaScript: The Good Parts he recommends that we use functional inheritance. Here\'s an example:
var mammal = function(spec, my
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.