Chapter 3. Object()

Conceptual Overview of Using Object() Objects

Using the built-in Object() constructor function, we can create generic empty objects on the fly. In fact, if you remember back to the beginning of Chapter 1, this is exactly what we did by creating the cody object. Let’s re-create the cody object.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var cody = new Object(); // create an empty object with no properties

for (key in cody) { // confirm that cody is an empty generic object
   if(cody.hasOwnProperty(key)) {
       console.log(key); /* should not see any logs, 
                         because cody itself has no properties */
   }
}

</script></body></html>

Here, all we are doing is using the Object() constructor function to create a generic object called cody. You can think of the Object() constructor as a cookie cutter for creating empty objects that have no predefined properties or methods (except, of course, those inherited from the prototype chain).

Note

If it’s not obvious, the Object() constructor is an object itself. That is, the constructor function is based on an object created from the Function constructor. This can be confusing. Just remember that like the Array constructor, the Object constructor simply spits out blank objects. And yes, you can create all the empty objects you like. However, creating an empty object like cody is very different than creating your own constructor function with predefined properties. Make sure you grok that cody is just an empty object based on the Object() ...

Get JavaScript Enlightenment now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.