Object-Oriented JavaScript
Densified from Introduction to Object-Oriented JavaScript
JavaScript objects (functions) are based on another object. The objects (base-)properties and functions are members of its prototype. See following properties for first mention of prototype.
Class:
function Person() { }
Instantiation:
var person1 = new Person();<span class="plain"><span style="font-family: Courier New;">
var person2 = new Person();</span></span>
Constructor:
function Person() {
alert('Person instantiated');
}
Properties:
function Person(gender) {
this.gender = gender;
alert('Person instantiated');
}
Person.prototype.gender = 'Person Gender';
Methods:
Person.prototype.sayGender = function() { alert(this.gender); };
Can then be used.
var person1 = new Person('Male');
var genderTeller = person1.sayGender;
person1.sayGender(); // alerts 'Male'
genderTeller(); // alerts undefined
alert(genderTeller === person1.sayGender); // alerts true
alert(genderTeller === People.prototype.sayGender); // alerts true
genderTeller.call(person1); //alerts 'Male'
Inheritance:
Single-class-inheritance only.
function Student() {
// Call the parent constructor
Person.call(this);
}
// inherit Person
Student.prototype = new Person();
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
// replace the sayGender method
Student.prototype.sayGender = function(){
alert('hi, I am a student');
}
Abstraction
var foo = function(){}; alert( 'foo is a Function: ' + (foo instanceof Function) ); alert( 'foo.prototype is an Object: ' + (foo.prototype instanceof Object) );
Encapsulation
?
Polymorphism
?