/* MJS UNDERSTANDING PROTOTYPES pg539 */
/*The ability to retroactively change a prototype even allows you to change the
defnition of objects built into JavaScript, such as String. This next bit of code adds
a trim() method to the String object, if it doesn’t already have one:*/
if (typeof String.prototype.trim == ‘undefined’) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,’’);
};
}
/* pg540 */
/* The best use of this concept is to create backwards-functional objects, as in the
String.prototype.trim() example (i.e., creating a String object that can be used
reliably regardless of the browser type or version).
Each method added to a prototype is therefore added to every instance of that
prototype, whether it is needed or not. If you only need a function for a specifc
instance, you can create that function separately and call it while providing the object:*/
/*
function doSomething(obj) {
// Do something with obj.
}
*/
function trimIt(obj) {
if (typeof String.prototype.trim == ‘undefined’) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,’’);
};
}
}
/* OR */
/* Or you could add the function defnition to just the single instance:*/
/*
var obj = {};
obj.doSomething = function() {
// Do something with this.
}
*/
var obj = {};
obj.doSomething = function() {
// Do something with this.
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.