Object.create()
1 |
var a = Object.create(Hero.prototype); |
This method creates a new object extending the prototype object passed as a parameter.
var b = {}
This is equivalent to Object.create(null) method, using a null prototype as an argument.
Using function constructor with new
1 2 3 4 5 6 7 8 |
function Website(newName) { var p_Name = newName || "not entered"; this.display = function() { console.log("Your website is called: " + p_Name); } } var a = new Website("www.hallo.com"); a.display(); |
es6 classes
1 2 3 4 5 6 |
class myObject { constructor(name) { this.name = name; } } var e = new myObject("hello"); |
Singleton pattern
1 2 3 |
var l = new function(){ this.name = "hello"; } |
literal vs instances
https://www.internalpointers.com/post/object-literals-vs-constructors-javascript
1 2 3 4 5 6 7 8 |
function Website(newName) { var p_Name = newName || "not entered"; this.display = function() { console.log("Your website is called: " + p_Name); } } var a = new Website("www.hallo.com"); a.display(); |
You have just created a JavaScript object called Website.
The main difference here is what you can do with it.
With the constructor function notation you create an object that can be instantiated into multiple instances with the new keyword
while the literal notation delivers a single object, like a singleton.
1 2 3 4 5 6 7 8 |
var Website = { 'url': 'http://www.internalpointers.com', 'printUrl': function() { console.log(this.url); } }; Website.printUrl(); |