Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these object literals?

Tags:

javascript

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?

like image 380
Nico Richter Avatar asked Jul 30 '21 13:07

Nico Richter


People also ask

What is difference between template literals and object literals?

Objects are created in the memory, Object literal is just a way to create an object, Template Literal is a string which can contain embedded expressions.

What is the meaning of object literals?

Object Literal. In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions. Here's a snippet of an object literal with one property and one function.

What are object literals in Python?

Objects are also called data structures. Python comes with some built-in objects. Some are used so often that Python has a quick way to make these objects, called literals. The literals include the string, unicode string, integer, float, long, list, tuple and dictionary types.

What are object literals in Java?

In JavaFX, objects are instantiated using object literals. This is a declarative syntax using the name of the class that you want to create, followed by a list of initializers and definitions for this specific instance.


1 Answers

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

like image 75
adiga Avatar answered Oct 19 '22 19:10

adiga