SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict Divisive Cotton's Avatar
    Join Date
    Jun 2008
    Location
    Andy lives in London, UK
    Posts
    393
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    The prototype object

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

    Take this little slice of Douglas Crockford script:

    Code:
    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?

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

  2. #2
    SitePoint Wizard
    Join Date
    Dec 2003
    Location
    USA
    Posts
    2,582
    Mentioned
    29 Post(s)
    Tagged
    0 Thread(s)
    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.
    Code:
    function Person() {}
    If I do this:
    Code:
    Person.sayHi = function() { console.log("Hi") }
    I can do this:
    Code:
    Person.sayHi();
    So Person itself has sayHi, but not objects of type Person.
    Code:
    var p1 = new Person();
    p1.sayHi(); // undefined
    If I prototype it, new Persons will have sayHi()
    Code:
    Person.prototype.sayHi = function() { console.log("Hi") }
    
    var p1 = new Person();
    p1.sayHi(); // works
    Make sense?

  3. #3
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,266
    Mentioned
    18 Post(s)
    Tagged
    0 Thread(s)
    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/Jav...ts/String/Trim

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

  4. #4
    SitePoint Addict Divisive Cotton's Avatar
    Join Date
    Jun 2008
    Location
    Andy lives in London, UK
    Posts
    393
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the feedback peeps. That makes sense.
    Let everyday be Christmas


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •