Closures make JavaScript OO
- "The
newkeyword creates an object that class constructors run inside of, thereby imprinting them - Functions are always closures (combine w/ previous rule to create OOP)"
Objects don't really exist in JavaScript: an object = a constructor function. So when you say:
var Richard = new Person();
you are creating a new instance of the Person function. Consider the following:
- function Person() {
- this.name = "Joe";
- }
- function Employee() {
- Employee.prototype = new Person();
- Employee.prototype.constructor = Employee;
- }
- var joeEmp = new Employee();
- alert (joeEmp.name); // shows "Joe"
This works because Employee is a closure (in line 8) so inherits the environment and variables in which it was called i.e. the name property of the Person class:
function Employee() -> function Person()
Note also line 6. This is important - otherwise Employee forgets what it is! It starts thinking that it = Person! Normally we do not have to set the constructor property but when we reassign the prototype property we need explicitly to declare what this function is. This is done by specifying the constructor property.
I found Kevin Linsey's post on inheritance very helpful in writing this and intend to read more about superclassing, something that doesn't normally exist in JavaScript, but for which Kevin has a solution.
