Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h1>The <code>prototype</code> object</h1> <p>The idea of the <code>prototype</code> 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 <code>prototype</code> of a predefined object, such as an <code>Array</code> or <code>String</code>, whenever a new object of that type is created, all of the methods and properties you defined to it's <code>prototype</code> will be copied to the new object.</p> <h2>How do I do it?</h2> <p>To do it, you simply follow the notation <code>Object.prototype.myProperty = value</code>, 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:</p> <h3>Example</h3> <pre><code>//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] </code></pre> <h2>What else should I be aware of?</h2> <p>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 <code>Array.prototype.empty()</code>. 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 <code>Array.prototype.mylibEmpty()</code> instead.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload