The prototype object

I’m a bit confused about the correct use of the prototype object

Take this little slice of Douglas Crockford script:

if (!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^\\s*(\\S*(?:\\s+\\S+)*)\\s*$/, "$1");
    };
}

http://javascript.crockford.com/remedial.html

That does what it does - remove unnecessary white space from the beginning and end of the string

However, I removed the prototype property like below and it seems to work just the same.

So what is the correct use of this prototype?


if (!String.trim) {
    String.trim = function () {
        return this.replace(/^\\s*(\\S*(?:\\s+\\S+)*)\\s*$/, "$1");
    };
}

Prototype makes the function available to all objects of that type.
Without prototype, it makes it so the String object (function) has that function.

Let’s not use String as an example since it’s tricky. Let’s use a custom object, say Person.


function Person() {}

If I do this:


Person.sayHi = function() { console.log("Hi") }

I can do this:


Person.sayHi();

So Person itself has sayHi, but not objects of type Person.


var p1 = new Person();
p1.sayHi(); // undefined

If I prototype it, new Persons will have sayHi()


Person.prototype.sayHi = function() { console.log("Hi") }

var p1 = new Person();
p1.sayHi(); // works

Make sense?

Divisive Cotton, the reason why trim worked just the same without prototype is because the trim method is already available in modern browsers. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim

Try your same test in IE8 or lower, and you’ll see that your second example will produce an error message.

Thanks for the feedback peeps. That makes sense.