Give an extend capacity to Object class. OOP in javascript is more convenient now ! (I hope)
What’s in there ?
Object.prototype
get 2 extra things :Parent
: A pointer to parent’s prototype. In the case ofObject
:Parent = null
, because it is the super classparent()
: An helper to call parent’s methods.
Object
get a static method callextend
which allow to extend this super class.
Actually all the futur classes will have thoses methodes and attributes.
Create a class
Use :
var MyClass = ParentClass.extend( prototype );
prototype
is obviously theprototype
ofMyClass
(i.e an object{}
of methods).- If you define a
constructor
, it will be call as the constructor of your class. - Even if the
prototype
is empty, it containsparent()
andParent
(see below). - Now
MyClass
can be extanded too. - You can pass an empty prototype and define methods after.
var MyClass = ParentClass.extend( {} );
// or
var MyClass = ParentClass.extend();
// add methods :
MyClass.prototype.myMethod = function(){
//...
};
// WARNING : do not override the prototype because it will break the legacy
MyClass.prototype = {
myMethod : function(){
// THIS IS BAD :)
}
};
Example :
var Simpson = Object.extend({
constructor : function( name ){
this.name = name;
},
sayHello : function(){
return 'Hello I am ' + name + ' Simpson!';
}
});
var homer = new Simpson('Homer');
alert( homer.sayHello() ); // Hello I am Homer Simpson!
Access to parent class
Use (inside the class) :
// attribute
this.Parent.myVar ;
// GrandParent attribute
this.Parent.Parent.myVar ;
// call parent method via Parent
this.Parent.myMethod.call(this, param1 , ... );
// or easier with .parent()
this.parent('myMethod', param1 , ...);
Example :
var SimpsonChild = Simpson.extend({
constructor : function( name , age ){
this.age = age;
// call parent constructor
this.parent('constructor',name);
},
// overriding parent class
sayHello : function(){
return this.parent('sayHello') + ' I am only ' + this.age + ' years old.';
}
});
var bart = new SimpsonChild('Bart',10);
alert ( bart.sayHello() ); // Hello I am Bart Simpson! I am only 8 years old.