ref –
- https://coderwall.com/p/p5cf5w/different-ways-of-creating-an-object-in-javascript
- http://chineseruleof8.com/code/index.php/2019/10/04/pure-prototype-inheritance-with-object-create/
- http://chineseruleof8.com/code/index.php/2018/04/13/object-create/
Object() constructor
1 |
var d = new Object(); |
Object.create()
1 |
var a = Object.create(null); |
a references an object, with its __proto__ pointing to undefined.
ref – http://chineseruleof8.com/code/index.php/2018/04/13/object-create/
Shorthand
1 |
var b = {}; |
b references an object, with its __proto__ pointing to default Object Prototype. Which has property constructor referencing to default Object function constructor. And of course, the default Object constructor has prototype reference back to the Object Prototype.
Using new to create instance
Given function
1 2 3 |
var Obj = function(name) { this.name = name } |
Explain this:
1 |
var c = new Obj("hello"); |
JS goes into 3 steps.
First, it identifies the function:
Second, it creates the instance:
1 |
c = Object.create(Obj.prototype) |
Third, it initializes the instance:
1 |
Obj.call(c, "hello"); |
which goes something like this:
1 2 3 4 |
function Obj(c, "hello") { this = c; this.name = "hello"; } |
All three steps is combined to create an instance object.
As a Singleton
1 2 3 |
var l = new function() { this.name = "hello"; } |
or using IIFE
1 2 3 4 5 6 7 |
var rtScript = (function() { var gCounter = 0; return { toString: function {...} add: function{...} } })(); |
ref – http://chineseruleof8.com/code/index.php/2017/10/12/immediately-invoked-function-expression/