1

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?

4 Answers 4

11
String.prototype.alertDialog = function() { alert(this); };
Sign up to request clarification or add additional context in comments.

Comments

6

String.prototype is the string prototype.

4 Comments

Whats the convention there anyways?
Every object should be capitalized : Object, String, Regexp, Number, Date, etc ...
The convention is that Constructors are capitolized. objects do not have to be capitolized, and should be, lest they be confused with Constructors
In my head I was thinking about constructors, not objects :)
3

You can extend the String class by referencing

String.prototype.yourFunction = function() {}

1 Comment

And this inside the function will refer to the string the method is being called on.
2

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();

1 Comment

Who's going to do a for loop on a String? And you should not use a for in with Arrays either. However, for maximum compatibility, it's best not to modify the prototype of native JS object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.