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. Lets recreate the cody object.
Sample: sample69.html
<!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).
If its 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 understand that cody is just an empty object based on the Object()
constructor. To really harness the power of JavaScript, you will need to learn not only how to create empty object containers from Object()
, but also how to build your own "class" of objects (Person()
) like the Object()
constructor function itself.
Object()
Parameters
The Object()
constructor function takes one optional parameter. That parameter is the value you would like to create. If you provide no parameter, then a null
or undefined
value will be assumed.
Sample: sample70.html
<!DOCTYPE html><html lang="en"><body><script> // Create an empty object with no properties. var cody1 = new Object(); var cody2 = new Object(undefined); var cody3 = new Object(null); console.log(typeof cody1, typeof cody2, typeof cody3); // Logs 'object object object'. </script></body></html>
If a value besides null
or undefined
is passed to the Object
constructor, the value passed will be created as an object. So theoretically, we can use the Object()
constructor to create any of the other native objects that have a constructor. In the next example, I do just that.
Sample: sample71.html
<!DOCTYPE html><html lang="en"><body><script> /* Use the Object() constructor to create string, number, array, function, Boolean, and regex objects. */ // The following logs confirm object creation. console.log(new Object('foo')); console.log(new Object(1)); console.log(new Object([])); console.log(new Object(function () { })); console.log(new Object(true)); console.log(new Object(/\bt[a-z]+\b/)); /* Creating string, number, array, function, Boolean, and regex object instances via the Object() constructor is really never done. I am just demonstrating that it can be done. */ </script></body></html>
Object()
Properties and Methods
The Object()
object has the following properties (not including inherited properties and methods):
Properties (Object.prototype;
):
Object()
Instance Properties and Methods
Object()
object instances have the following properties and methods (does not include inherited properties and methods):
Instance Properties (var myObject = {};
myObject.constructor;
):
Instance Methods (var myObject = {};
myObject.toString();
):
The prototype chain ends with Object.prototype
, and thus all of the properties and methods of Object()
are inherited by all JavaScript objects.
Creating Object()
Objects Using "Object Literals"
Creating an "object literal" entails instantiating an object with or without properties using braces (var cody = {};
). Remember at the beginning of Chapter 1 when we created the one-off cody object and then gave the cody object properties using dot notation? Let's do that again.
Sample: sample72.html
<!DOCTYPE html><html lang="en"><body><script> var cody = new Object(); cody.living = true; cody.age = 33; cody.gender = 'male'; cody.getGender = function () { return cody.gender; }; console.log(cody); // Logs cody object and properties. </script></body></html>
Notice in the code that creating the cody
object and its properties took five statements. Using the object literal notation we can express the same cody
object in one statement.
Sample: sample73.html
<!DOCTYPE html><html lang="en"><body><script> var cody = { living: true, age: 23, gender: 'male', getGender: function () { return cody.gender; } }; // Notice the last property has no comma after it. console.log(cody); // Logs the cody object and its properties. </script> </body>
Using literal notation gives us the ability to create objects, including defined properties, with less code and visually encapsulate the related data. Notice the use of the :
and ,
operators in a single statement. This is actually the preferred syntax for creating objects in JavaScript because of its terseness and readability.
You should be aware that property names can also be specified as strings:
Sample: sample74.html
<!DOCTYPE html><html lang="en"><body><script> var cody = { 'living': true, 'age': 23, 'gender': 'male', 'getGender': function () { return cody.gender; } }; console.log(cody); // Logs the cody object and its properties. </script> </body>
Its not necessary to specify properties as strings unless the property name:
- Is one of the reserved keywords (
class
). - Contains spaces or special characters (anything other than numbers, letters, the dollar sign ($), or the underscore (_) character).
- Starts with a number.
Careful! The last property of an object should not have a trailing comma. This will cause an error in some JavaScript environments.
All Objects Inherit From Object.prototype
The Object()
constructor function in JavaScript is special, as its prototype
property is the last stop in the prototype chain.
In the following sample, I augment the Object.prototype
with a foo
property and then create a string and attempt to access the foo
property as if it were a property of the string instance. Since the myString
instance does not have a foo
property, the prototype chain kicks in and the value is looked for at String.prototype
. It is not there, so the next place to look is Object.prototype
, which is the final location JavaScript will look for an object value. The foo
value is found because I added it, thus it returns the value of foo
.
Sample: sample75.html
<!DOCTYPE html><html lang="en"><body><script> Object.prototype.foo = 'foo'; var myString = 'bar'; // Logs 'foo', being found at Object.prototype.foo via the prototype chain. console.log(myString.foo); </script> </body>
Conclusion
Careful! Anything added to Object.prototype
will show up in a for in
loop and the prototype chain. Because of this, its been said that changing Object.prototype
is forbidden.
Comments