JavaScript中字符串的prototype属性在哪里?

时间:2009-11-12 22:23:43

标签: javascript string

我刚注意到JavaScript中的字符串上没有原型属性。

这是一个教学问题,而我试图围绕JavaScript类型系统,但是给出了什么?

"abc".toString()如何运作?我将如何扩展字符串?如果我希望能够以"hey you!".alertDialog()为例?

4 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分:6)

String.prototype是字符串原型。

答案 2 :(得分:3)

您可以通过引用

扩展String类
String.prototype.yourFunction = function() {}

答案 3 :(得分:2)

在弄乱原型和对象数据类型时发出警告,如果使用for循环,则完整函数将作为键/值对之一返回。请参阅下面的基本示例和评论。

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