HTML and CSS Reference
In-Depth Information
Adding a member to a JavaScript object works only for that particular instance. If you were now to
create another instance of the Number object, the property type would not be available for the new
Number object. You can work around that problem by using prototypes.
The prototype common property
If you want to add a new member to all instances being created of a given type, you have to add the
member to the object's prototype. Here's how to add a type property to all the numbers so that you
gain more control over the effective type of the object.
if (typeof Number.prototype.type === 'undefined') {
Number.prototype.type = "Number";
}
Important The example you just examined, and specifically the use of a custom type
property, is not coincidental. In JavaScript, you can use the typeof operator on a variable
name to discover the type of an object currently stored in the variable. However, most
of the time all you get back as a response is the word “Object.” There is no easy way to
distinguish between, for example, strings and numbers. For this reason, the use of a custom
type property makes even more sense.
Creating new object instances
You can use the Object type to create aggregates of values and methods, which is the closest you
can get in JavaScript to standard object-orientation, such as C#. Here's a possible way to create a new
object:
var dog = new Object();
dog.name = "Jerry Lee Esposito";
In general, the direct use of the constructor of an Object is disregarded. A better approach entails
using an object literal, as shown below:
var dog = {
name: "Jerry Lee Esposito",
};
Using the constructor of an Object poses some performance issues to the JavaScript interpreter,
which has to resolve the scope of the constructor call and look up a potentially large stack.
In addition, using the constructor directly also doesn't transmit the sense of objects as dictionaries,
which is a key point of JavaScript programming.
Search WWH ::




Custom Search