Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if an object is an object literal in Javascript?

Tags:

Is there any way to determine in Javascript if an object was created using object-literal notation or using a constructor method?

It seems to me that you just access it's parent object, but if the object you are passing in doesn't have a reference to it's parent, I don't think you can tell this, can you?

like image 972
leeand00 Avatar asked Jul 23 '09 18:07

leeand00


People also ask

What is an object literal in JavaScript?

A JavaScript object literal is a comma-separated list of name-value pairs wrapped in curly braces. Object literals encapsulate data, enclosing it in a tidy package. This minimizes the use of global variables which can cause problems when combining code.

What is difference between object and object literal in JavaScript?

Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.

What character defines an object literal?

Object literals. An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).


1 Answers

What you want is:

Object.getPrototypeOf(obj) === Object.prototype 

This checks that the object is a plain object created with either new Object() or {...} and not some subclass of Object.

like image 176
Jesse Avatar answered Oct 06 '22 01:10

Jesse