Reputation: 379
I created two Objects. The first one is working as intended.
let working = {constructor: function(){
console.log("working");
}};
let notworking = {constructor(){
console.log("notworking");
}}
new working.constructor();
new notworking.constructor();
But the second one throws an Error. The Error message is:
Uncaught TypeError: notworking.constructor is not a constructor
Tested on Firefox and Chrome.
In Firefox DevTools the Object itself looks the same. There is a difference in the constructor method. The working constructor has properties arguments, caller, length and name. The notworking constructor has only the properties length and name.
So what is the difference between these two objects or constructors?
Upvotes: 6
Views: 191
Reputation: 35259
The second syntax is the method syntax and it was introduced in ECMAScript 2015. They are almost equivalent, but there's a difference. In the first object, constructor
is just a key whose value is a function. In the second object, constructor
is a method. Method definitions are not constructable
Methods cannot be constructors. They will throw a TypeError if you try to instantiate them
From: MDN
Upvotes: 4