开发者

Where is the prototype property on strings in JavaScript?

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!".alert开发者_运维知识库Dialog() for example?


String.prototype.alertDialog = function() { alert(this); };


String.prototype is the string prototype.


You can extend the String class by referencing

String.prototype.yourFunction = function() {}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜