Monday 5 December 2016

Javascript: prototype and construct

Equation 1: Object.prototype.[[prototype]] == null
Equation 2: Function.prototype.[[prototype]] === Object.prototype
Equation 3: Func.[[prototype]] == Function.prototype
Equation 4: Object.create(Obj).[[prototype]] = Obj
Equation 5: obj.[[prototype]] === obj.constructor.prototype
Equation 6: Object.prototype.prototype == undefined
Equation 7: Func.constructor === Function
Equation 8: Func.prototype.constructor === Func
Rule 1: When a property cannot be found on an obj, consult obj.[[prototype]], if still not found, consult obj.[[prototype]].[[prototype]] until reaching the end of chain (null)


I sorted these equations in the hope to explain the 'myths' around the prototype, constructor, and [[prototype]] (aka __proto__)

Let's see.

 

Exercise 1

Prove:
var obj = {};
Console.log(obj.prototype === undefined)

Solution:

obj doesn't have the property prototype on its own, it needs to consult obj.[[prototype]]. //Rule 1

obj.[[prototype]] === obj.constructor.prototype  //Equation 5
obj.constructor === Object //WHY?
obj.[[prototypte]] === Object.prototype

Object.prototype is the end of the chain because Object.prototype.[[prototype]] === null; //Equation 1

obj.prototype === obj.[[prototypte]].prototype === Object.prototype.prototype === undefined //Equation 6

 

Exercise 2

Prove:
var obj = new Object(2);
Console.log(obj.prototype === undefined);

Solution:

obj.[[prototype]] === obj.constructor.prototype  //Equation 5
obj.constructor === Number //WHY?
obj.[[prototype]] === Number.prototype

Number.prototype also doesn't have property prototype on its own, it needs to consult Number.prototype.[[prototype]] //Rule 1

Number.prototype.[[prototype]] === Object.prototype //Equation 2

obj.prototype === Number.prototype.[[prototype]].prototype === Object.prototype.prototype === undefined //Equation 6

Exercise 3

Prove:
var obj = Object.create(Object);
Console.log(obj.prototype === Object.prototype);

Solution:
obj.[[prototype]] === Object; //Equation 4
obj.prototype === obj.[[prototype]].prototype = Object.prototype //Rule 1

 

Exercise 4

Prove:
Console.log (Object.getPrototypeOf(Object) === Function.prototype); //true

Solution:
Object.[[prototype]] ===  Function.prototype; //Equation 3

Exercise 5

Prove:

var obj = new Function();
Console.log(Object.getPrototype(obj) === Function.prototype);

Solution:
typeof 'new Function()' is also a function!

obj.[[prototype]] === Function.prototype; //Equation 3


Note: Those lines with //WHY are the ones that I am unable to account for. Strictly speaking, new Object(2) doesn't even have a constructor property on its own. There are some circular arguments around equation 5. For now, I just tell the object's constructor by looking at its definition --- new Object(2) is a Number, "123" is also a Number, "ABC" is a String, etc. The ones that I cannot tell are Objects.This assumption could be deeply flawed. Will find out..