Inheritance Patterns
Difference between Prototype and Class: FunFunFunction #46
Three types:
- Functional
- Prototypal
- Pseudoclassical
Functional (Factory Functions)
- Simple to understand
- More flexible, more robust
- Better code readability
- Don't have to use the 'this' keyword
- Possible to have private variables
var Person = function(name, age) {
//Instantiate an object and add "constructor" properties
var obj = {
name: name,
age: age,
}
// now you can add methods to the object:
obj.sayName = function() {
console.log("Hello, my name is " + this.name)
}
return obj
}
//What would a child "Class" look like here?
var Girl = function(name, age) {
var obj = Person(name, age)
obj.gender = 'Female'
obj.declareGender = function() {
console.log('I am a ' + this.gender)
}
return obj
}
Prototypal
- Extreme Performance
- Created faster and use less memory
- ~ 10,000 items per frame+ is when to use this
- Prototypes are not copies of properties or methods, they are delegates
var Person = function(name, age) {
var obj = Object.create(Person.prototype)
obj.name = name
obj.age = age
return obj
}
// adding a prototype method
Person.prototype.sayName = function() {
console.log('Hello, my name is ', this)
}
// to instantiate
var bobby = new Person('Bobby', 23)
Pseudoclassical
- Similar to Prototypal
- Instead of copying all methods when creating a new object it delegates reusable properties through prototypes
var Person = function(name, age) {
/* this = Object.create(Person.prototype) */
this.name = name
this.age = age
/* return this */
}
Person.prototype.sayName = function() {
console.log('Hello, my name is ', this.name)
}
// -------------- Now for the children! --------------
var Boy = function(name, age, weight) {
// Bind 'this' keyword and pass down the constructor arguments
Person.call(this, name, age)
this.weight = weight
}
// How do we make sure that Person prototypes delegate to Boy prototype?
Boy.prototype = Object.create(Person.prototype)
// This will ensure that the constructor delegates to the correct location. It insures that
// and objects created using Boy are instances of Boy
Boy.prototype.constructor = Boy
// You can also add any methods that need to be added
Boy.Prototype.pee = function() {
console.log('I am peeing while standing!!')
}
Other Notes
Object.create( ) :