Well firstly, this post is on nothing new and undiscovered. It's just a very simple example that shows you how JavaScript inheritance works. I usually use this as a class template and starting point for my JavaScript projects. This is also called the Pseudo Classical pattern for JavaScript inheritance.
Full credit needs to go to the series of articles I read at http://livingmachines.net/tag/creating-javascript-classes-series/ and if you're keen to learn more on this topic, I highly recommend you read all the articles over there. I just took the core ideas from that series and created a single, reusable example.
// a universal object that's used prevent parent classes from // executing their full constructors when a child inherits from it // (see how it is used below) var inheriting = { }; /* ----- Parent Class */ Person = function(params) { if (arguments[0] === inheriting) { return; } this.firstName = params.firstName; this.lastName = params.lastName; }; Person.prototype.sayHello = function(){ alert("Hello " + this.firstName + " " + this.lastName); }; /* ----- Child Class */ Employee = function(params) { // we need the 'own properties' of the Person superclass, // so call the Person suplerclass constructor with context of the current object // this gives our Employee object instance the properites of Person Person.apply(this, arguments); this.company = params.company; }; // create a reference to Person's prototype only (don't execute the person's full constructor). // This sets up "method inheritance" where the methods are inherited by the child Employee.prototype = new Person(inheriting); // inheriting from the parent overrides the child's constructor property, this fixes it // (may cause problems later on if you work with child.prototype.constructor) Employee.prototype.constructor = Employee; // keep a reference to the parent's items so we can call them even if we // overwrite in child classes Employee.base = Person.prototype; Employee.prototype.sayHello = function(useOwn){ if (useOwn) { alert("Hello " + this.firstName + " " + this.lastName + ", from " + this.company); } else Employee.base.sayHello.call(this); }; /* ----- Instance of Child */ var markPaul = new Employee({firstName: "Mark", lastName: "Paul", company: "Acme Explosives"}); // alerts "Hello Mark Paul" markPaul.sayHello(false); // alerts "Hello Mark Paul, from Acme Explosives" markPaul.sayHello(true);
Full credit needs to go to the series of articles I read at http://livingmachines.net/tag/creating-javascript-classes-series/ and if you're keen to learn more on this topic, I highly recommend you read all the articles over there. I just took the core ideas from that series and created a single, reusable example.
No comments:
Post a Comment