JavaScript only has objects with private property called prototype
linked to
another object which is the prototype of said object. That prototype also has
its own prototype object all the way until the final reference of null
.
All JavaScript objects are instances of Object
object under null
.
JavaScript objects are dynamic bags of properties. When looking for a property of an object, it will be searched not only in the original object but also in its prototype object and subsequent ancestor prototype objects. The property is undefined if it is found along the prototype chain.
func.prototype
is used to assign `[[PROTOTYPE]]`` to all instances created by
the function as a constructor.
Object.prototype
represents the Object
prototype object.
Property shadowing is when an object uses its own property while inheriting another object with the property of the same name as prototype.
For inherited functions, it's the same as method overriding in OOP. When
executing such functions, this
refers to the object inheriting the function,
not the prototype.
Arrow function does not have default prototype
property.
Creating objects can be done with
- Syntax constructs
- Constructor
Object.create
class
keyword
Lookup times on properties up in prototype chain will take longer and searching for non existent properties will traverse the full prototype chain.
When iterating over properties of an object, every enumerable property in
prototype chain will be enumerated. To prevent that hasOwnProperty
method is
required.
Monkey Patching is extending Object.prototype
or other built-in prototype
and breaks encapsulation and not recommended. To use this, the function with
prototype extended must be initialized which may put unwanted methods onto the
project.
Object.create
can also be used to extend.
/* __proto__ is Object.prototype */
const obj = { a: 1 };
/* __proto_ is Array.prototype which prototype is null */
const arr = [ "a", "b", "c" ];
function f () { return false; }
function g (){
this.h = [];
this.i = [];
}
g.prototype.j = [];
/*
* Has h and i as own properties because of this keyword
* gg.__proto__ is g.prototype when new g() is executed
*/
const gg = new g();
const a = { a : 1 };
const b = Object.create(a);
b.a = 5; //a.a remiains 1
delete b.a; //b.a is 1 again due to Inheritance
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
class Square extends Polygon {
constructor(sideLength) {
super(sideLength, sideLength);
}
get area() {
return this.height * this.width;
}
set sideLength(newLength) {
this.height = newLength;
this.width = newLength;
}
}
const sq = new Square(2);