简体   繁体   中英

What is the difference between these object literals?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM