views:

57

answers:

2

I trying to learn how to create prototypes in Javascript, but the Array prototype confuses me. I have an Array of Numbers that are stored in the Array as Strings, and I want to convert the entire Array so they are actual numbers. How do I do this an exactly what would I type to activate this prototype?

+1  A: 

I'm not sure exactly how you want to use prototypes. But a simple way to get an array of numbers from an array of strings is:

var numArray = strArray.map(parseFloat);

For browsers that don't support ECMAScript 5, you can get a fallback implementation of map from MDC.

Matthew Flaschen
A: 

The prototype object

The idea of the prototype object is that it is an object off which all new objects of that type will get their methods and properties off. By adding to the prototype of a predefined object, such as an Array or String, whenever a new object of that type is created, all of the methods and properties you defined to it's prototype will be copied to the new object.

How do I do it?

To do it, you simply follow the notation Object.prototype.myProperty = value, so in your case you want to add a method which converts the entire array of Strings into numbers, here is a simple example of how you would do it:

Example

//So here, you see the definition of your new method
//Note the use of the 'Object.prototype.property = value' notation
Array.prototype.stringsToNumbers = function()
    { //I use the Whitesmiths indentation style, get over it :p

    //To refer to the object which the method was called on use the
    //'this' keyword.
    for (index in this)
        {
        if (typeof(this[index]) === 'string') //Always typecheck... Always.
            {
            this[index] = parseFloat(this[index]);
            }
        }

    //Sometimes you want to return the object to allow for chaining.
    return this;
    }

//You would then use it like this:
var myArray = ["23","11","42"];
myArray.stringsToNumbers();
//myArray now contains [23,11,42]

What else should I be aware of?

Arguably, the largest danger of prototyping native objects is that there creates a chance of collisions with other third party code, especially when extending the native objects with relatively common methods, such as Array.prototype.empty(). Take this into account while prototyping native objects, especially with the naming of your methods and properties. Consider adding a prefix to the method if you believe there is a chance of a collision, so use Array.prototype.mylibEmpty() instead.

Andrew Dunn