Number(132).toString(2);
What I did yesterday?
Learned about react portals
What I’m doing today?
Finish implementing react portals
What is blocking me?
What is a JS prototype?
JS prototype are mechanisms that allows JS objects to inherit features from one another
What is JS inheritance?
Objects in JavaScript are dictionaries. Each of them has a magic proto field that can point to any object which will be the prototype of the first one.
When you look up a field on the object using either obj.field or obj[“field”] syntax (they are different way of doing the same thing), and the field is not present in the object, the JS runtime looks for the same field on the prototype. If the field still can’t be found, the property is looked up on the prototype of the prototype, etc…
const a = { x: 5 };
console.log(a.x, a.y, a.z); // 5, undefined, undefined; there’s no y or z here
But if we add a prototype:
a.proto = { y: 6 };
console.log(a.x, a.y, a.z); // 5, 6, undefined; still no z, obviously
a.proto.proto = { z: 7 }
console.log(a.x, a.y, a.z); // 5, 6, 7
If you set a.y or a.z it will create those fields on a and will leave the prototypes alone:
a.z = 8;
console.log(a.z, a.proto.proto.z); // 8, 7
Constructors are a way to automate the initialization of the fields of an object, and assigning it’s prototype.
function B (y) {
this.y = y;
console.log(this.proto === B.prototype); // true
}
B.prototype.z = 7;
const b = new B(9);
console.log(b.y, b,z); // 9, 7
Here, calling new B(9) creates a new object under the scene, sets its proto to B.prototype, and passes it to the B function as this.
You can create further prototype chains:
function A() {
this.x = 5;
console.log(
this.proto === A.prototype,
this.proto.proto === B.prototype
);
}
A.prototype = new B(6)
const aa = new A()
console.log(aa.x, aa.y, aa.z); // 5, 6, 7
Calling new also does some magic such that the instanceofoperator also works.
Note that the this.proto === … lines are true only when the functions are called with the new operator.
If you call them normally, this will be null or point to the global object depending on whether you’ve enabled strict mode or not (or to foo if you use A.call(foo) or A.apply(foo)).