MJS Understanding Prototypes pg539

by Lucille Kenney

JavaScript

/* 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.
}