2. Basic JS Classes
Functions act as constructors
Functions have a prototype
Use new to create an instance of a type
Call instance methods with dot notation
3. function Animal() {
this.name = "animal";
}
Animal.prototype.speak = function() {
console.log("I'm a " + this.name);
};
var animal = new Animal();
animal.speak(); //logs "I'm a animal"
4. Object
All JS objects inherit from Object
Object has 2 standard methods:
toString
valueOf
Lot’s of non-standard and newer methods:
https://developer.mozilla.org/en/JavaScript/Reference/
Global_Objects/Object
5. Overriding Methods
Can override super class methods by:
attaching new methods to the prototype property
eg. Animal.prototype.toString = function() { ... }
7. Add methods to existing Classes
Add methods to the prototype of the existing class
All instances of the class will get those methods
You can extend built in classes too - with a couple of caveats
Generally bad to extend the prototype of Object
Generally accepted as bad to extend the prototype of
DOM classes, although MooTools and Prototype do this
9. Inheritance
Create a new constructor function
Assign a new instance of the base class to the prototype
function A { ... }
function B { ... }
B.prototype = new A;
10. function Pig() {
this.name = "pig";
}
Pig.prototype = new Animal;
var pig = new Pig();
pig.speak(); // logs "I'm a pig"
console.log(pig.toString()); // logs "[pig Animal]"
Animal.prototype.countLegs = function() {
return this.legs || 0;
};
Pig.prototype.legs = 4;
console.log(animal.valueOf() + " has " + animal.countLegs() +
↳" legs"); // logs "animal has 0 legs";
console.log(pig.valueOf() + " has " + pig.countLegs() +
↳" legs"); // logs "pig has 4 legs";
11. function Eisbein() {
this.legs = 1; // Instance variable
}
Eisbein.prototype = new Pig;
var eisbein = new Eisbein();
eisbein.speak(); // logs "I'm a pig"
console.log(eisbein.valueOf() + " has " +
↳eisbein.countLegs() + " legs");
↳// logs "pig has 1 legs";
12. Calling base class methods
Use Function#call to call the base class method in the context
of the current class
Base.prototype.method.call(this);
Call is useful in many other places too
Array.prototype.slice.call(arguments); //creates a real
array from the arguments oject