Adding properties to a literal in JavaScript

Credits: This tutorial is written and contributed by Alex Vincent. Alex is a long time visitor of JavaScript Kit, and participant of the CodingForums.

The problem:

Ever try to add properties to a function's argument, only to discover that argument just won't take properties?
x = "JavaScript"
function myFunc1(obj) {
	obj.myProp = new Object()
	// returns undefined when calling myFunc1(x)
It's quite annoying. In theory, you should be able to add properties and methods to any object you create in JavaScript. But in this case, you can't.

The misnomer

In JavaScript, every object has a constructor property, we are taught. In actuality, this isn't quite true. The constructor property is a function.  Therefore, it is more accurate to say every object has a constructor method.  By calling this method, you can create new objects of the same type as the original object:
var y = new obj.constructor()
What makes this so interesting is every object you create by this method you can add properties to.

The solution

Why not re-initialize the original object in this manner?
obj = new obj.constructor(obj)
This works!!  By giving the constructor method (or function, as the case may be) the object itself as an argument, it will return an exact copy of the original object.  We must declare the object using the new statement, however, to re-initialize the original object altogether. (Don't ask me why.  It just works that way.  It's more syntactically correct anyway.) Thus, the following produces the desired result:
y = "JavaScript"
function myFunc2(obj) {
	obj = new obj.constructor(obj)
	obj.myProp = new Object()
	// returns [object Object] when calling myFunc2(y)
Follow Us
Facebook Fan Page