##obj playground ###functions and methods
use strict
forcesthis
to beundefined
call apply bind
allow you to forcethis
to be certain value ###prototypal inheritance- js will go as far up the prototypal chain that it needs to in order to find the property, all while keeping the original
this
intact - polymorphism - same name, diff behaviors
var answer = {
get: function() {
return this.val;
},
val: 42
}
var firmAnswer = Object.create(answer);
firmAnswer.get = function() {
// return answer.get(); --> wrong! this would get rescoped to answer
return answer.get.call(this);
}
firmAnswer.val = 3.14
firmanswer.get(); // 3.14
###classes and instantiation
- constructor - common method to initialize objects
var AnswerPrototype = {
constructor: function fn0(value) {
this._val = value; // underscore means 'this is private, dont change'
},
get: function fn1() {
return this._val;
}
};
var lifeAnswer = Object.create(AnswerPrototype);
lifeAnswer.constructor(42);
var FirmAnswerPrototype = Object.create(AnswerPrototype);
FirmAnswerPrototype.get = function fn2() {
return AnswerPrototype.get.call(this) + '!!';
}
var magicAnswer = Object.create(FirmAnswerPrototype);
magicAnswer.constructor(3);
magicAnswer.get(); // 3!!
###the classical model
- every time you define a function...
- it creates a prototype with a
constructor
function that points back to the function you just created - you actually create two objects: the funciton object and then the prototype object that's just hanging out
- you are actually defining a constructor that is associated with a little do-nothing class
- it creates a prototype with a
- if meant to be a constructor, Capitalize it. if meant to be function, lowercase.
- define constructor first (
function Answer
). js will create obj to go along with that, with a constructor prop that points back to answer func. that prototype is our class.
function Answer(value) {
this._val = value;
}
Answer.prototype.get = function fn1() {
return this._val;
}
var lifeAnswer = new Answer(42);
lifeAnswer.get(); // 42
- subclasses
- need
FirmAnswer
prototype to extendAnswer.prototype
and at first it doesnt --FirmAnswer
gets its own prototype from js
function FirmAnswer(value) {
Answer.call(this, value);
}
FirmAnswer.prototype = Object.create(Answer.prototype);
FirmAnswer.prototype.constructor = FirmAnswer;
FirmAnswer.prototype.get = function fn2() {
return Answer.prototype.get.call(this) + '!!';
}
var luckyAnswer = new FirmAnswer(7);
luckyAnswer.get(); // 7!!
###instanceof
- js looks at prototype of constructor and compares it to the object
- looks at
Answer.prototype
property. then atlifeAnswers
actual prototype. if same obj, then yes
lifeAnswer instanceof Answer; //true
- js will look up prototype chain until it finds (or doesn't find) the prototype it's looking for (so a subclass is still an instanceof)
###future
- new syntax taht will make it easier to do classical model of inheritance
- e.g.
class Answer...