I. { }
: Literal Constructor
1
2
3
4
5
6var person = {
name = "Anand",
getName = function(){
return this.name
}
}
II. Object.create()
: can be used on inheritance
This can create a new object from another object as it prototype
More efficient to use a prototype if you are going to have multiple objects sharing properties or methods.
1
2
3
4
5let proto = {name: "default", foo: function() {}}
let obj1 = Object.create(proto); obj1.name = "a"
let obj2 = Object.create(proto); obj1.name = "b"
let obj3 = Object.create(proto); obj1.name = "c"
let obj4 = Object.create(proto); obj1.name = "d"
III. Function Constructor with this
& new
- Bad thing: every time, when we create an new object, it will occupy space for all attributes of
Person
Using
Prototype
1
2
3
4
5
6
7
8function Person(name){
this.name = name
this.getName = function(){
return this.name
}
}
let mycar = new Person('Eagle');
IV. Function Constructor & Prototype
prototype
is a shared object, where all its inheriting objects will share this same space, won’t create extra space for attributes inherited fromprototype
1
2
3
4
5
6
7
8
9
10
11
12
13
14function Graph() {
this.vertices = [];
this.edges = [];
}
Graph.prototype = {
addVertex: function(v) {
this.vertices.push(v);
}
};
var g = new Graph();
// g is an object with own properties 'vertices' and 'edges'.
// g.[[Prototype]] is the value of Graph.prototype when new Graph() is executed.
V. ES6 class
introduced a new set of keywords implementing classes. The new keywords include
class
,constructor
,static
,extends
, andsuper
.all functions except
constructor
are put into the prototype of that object (Square
)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
// inherit from another class
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;
}
}
// Use new to create object from class
var square = new Square(2);
VI. Singleton: one object of a kind
Singleton
is used on class-based languageIn jS, All objects created using literal constructor are singletons
1
2
3
4
5
6
7
8var Robot = {
metal: "Titanium",
killAllHumans: function(){
alert("Exterminate!");
}
};
Robot.killAllHumans();