HTML and CSS Reference
In-Depth Information
There is a solution to this problem that does not rely on reverting to classes: you could
simply clone an existing object, and change its properties as required. The object being
cloned can be referred to as a prototype for other objects.
We will see in later chapters that jQuery contains a helper for cloning objects, but for now
we will write our own clone implementation. This function will perform a deep clone on
an object: if a property on an object contains a value that is an object, that object will also
be cloned.
function clone(obj) {
if (obj == null || typeof obj != 'object') {
return obj;
}
var newObj = {}
for (var key in obj) {
newObj[key] = clone(obj[key]);
}
return newObj;
}
This function uses the for (var key in obj) loop to iterate through all the properties on
an object. This is a special kind of JavaScript loop specifically provided to iterate through
properties in an object. If the value of the property is an object, it is recursively passed to
the clone function. If it is a simple type (such as a number or string) it is returned imme-
diately so it can be set directly on the new instance of the object. You will remember from
earlier sections that strings and numbers are immutable; therefore they do not need to be
cloned.
This implementation should reinforce to you how simple JavaScript objects are.
//
There are potential problems with this implementation that have been ignored
for simplicity. This implementation should not be used in real applications: use
versions provided in the jQuery or Underscore libraries.
You can now use this function to construct a new object for storing information about
people:
> obj3 = clone(obj2)
 
Search WWH ::




Custom Search