Object Oriented JavaScript
ShevaXu opened this issue · comments
Sheva Xu commented
Object Oriented JavaScript
Notes From Udacity's Object Oriented JavaScript
Contents
this keyword
this
usually bound to the left-hand-side of .
when function get called (if no .
, then global
)
Prototype chain
Object.create
can specify prototype
v.s. deep copy of object properties (e.g., extend
)
Look up the chain when properties/keys not found
Object Decorator Pattern
var carlike = funciton (obj, loc) {
obj.loc = loc
obj.move = function (step) {
obj.loc += step // or use this.loc
}
return obj
}
// ...
var car = carlike({}, 0)
// or
var cab = {}
carlike(cab, 1) // or cab = ...
Functional Classes
a.k.a. Factory
var CarFactory = funciton (loc) {
var obj = { loc: loc }
extend(obj, CarFactory.methods) // extend is not native, it copys
return obj
}
CarFactory.methods = {
move: function (step) {
this.loc += step
}
}
// ...
var car = CarFactory(0)
Prototypal Classes
var Car = funciton (loc) {
var obj = Object.create(Car.prototype)
obj.loc = loc
return obj
}
Car.prototype.move = function (step) {
this.loc += step
}
// Car.prototype.constructor === Car // true
Pseudoclassical Patterns
var Car = funciton (loc) {
// this = Object.create(Car.prototype)
obj.loc = loc
// return this
}
Car.prototype.move = function (step) {
this.loc += step
}
// ...
var car = new Car(1)
new
make the above comment-out happen
Subclasses
var Van = function (loc) {
Car.call(this, loc)
}
Van.prototype = Object.create(Car.prototype)
Van.prototype.constructor = Van;
Van.prototype.grab = function () { ... }
//
var van = new Van(2)