title | comments | date | type | categories | tags |
---|---|---|---|---|---|
Create new Objects with Inheritance |
true |
2018-10-04 04:54:04 -0700 |
categories |
Full stack |
JavaScript Core |
-
var person = { name = "Anand", getName = function(){ return this.name } }
-
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.
-
let 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"
-
Bad thing: every time, when we create an new object, it will occupy space for all attributes of
Person
-
Using
Prototype
-
function Person(name){ this.name = name this.getName = function(){ return this.name } } let mycar = new Person('Eagle');
-
prototype
is a shared object, where all its inheriting objects will share this same space, won't create extra space for attributes inherited fromprototype
-
function 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.
-
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
) -
class 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);
-
Singleton
is used on class-based language -
In jS, All objects created using literal constructor are singletons
-
var Robot = { metal: "Titanium", killAllHumans: function(){ alert("Exterminate!"); } }; Robot.killAllHumans();
-