views:

91

answers:

4

I just noticed that there is no prototype property on strings in JavaScript.

This is a pedagogical question while I try to wrap my head around the JavaScript type system but what gives?

How come "abc".toString() works? And how would I go about extending strings? If I wanted to be able to do "hey you!".alertDialog() for example?

+6  A: 

String.prototype is the string prototype.

Fabien Ménager
Ooooh, capital S ...got it
George Mauer
Whats the convention there anyways?
George Mauer
Every object should be capitalized : Object, String, Regexp, Number, Date, etc ...
Fabien Ménager
The convention is that Constructors are capitolized. objects do not have to be capitolized, and should be, lest they be confused with Constructors
Breton
should/shouldn't/s
Breton
In my head I was thinking about constructors, not objects :)
Fabien Ménager
+9  A: 
String.prototype.alertDialog = function() { alert(this); };
ob
+2  A: 

You can extend the String class by referencing

String.prototype.yourFunction = function() {}
jaywon
+2  A: 

A word of warning when messing with prototype and Object data types, if you use a for loop, the full function will come back as one of the key/value pairs. See the basic examples below and comments.

// Basic hash-like Object
var test = {
    'a':1,
    'b':2,
    'c':3,
    'd':4
};

// Incorrect
// badAlerter prototype for Objects
// The last two alerts should show the custom Object prototypes
Object.prototype.badAlerter = function() {
    alert('Starting badAlerter');
    for (var k in this) {
     alert(k +' = '+ this[k]);
    }
};

// Correct
// goodAlerter prototype for Objects
// This will skip functions stuffed into the Object.
Object.prototype.goodAlerter = function() {
    alert('Starting goodAlerter');
    for (var k in this) {
     if (typeof this[k] == 'function') continue;
     alert(k +' = '+ this[k])
    }
};

test.badAlerter();
test.goodAlerter();
paulj