2009-09-11 60 views
6

我有一個原型模型,其中我需要包括以下擴展方法進原型:的Javascript原型擴展方法

String.prototype.startsWith = function(str){ 
    return (this.indexOf(str) === 0); 
} 

實施例: [JS]

sample = function() { 
    this.i; 
} 

sample.prototype = { 
    get_data: function() { 
     return this.i; 
    } 
} 

在原型模型中,我如何使用擴展方法或任何其他方式在JS原型模型中創建擴展方法。

回答

13

調用上線新的方法:如

String.prototype.startsWith = function(str){ 
    return (this.indexOf(str) === 0); 
} 

應儘可能簡單:

alert("foobar".startsWith("foo")); //alerts true 

對於你的第二個例子中,我假設你想有一個構造函數,將成員變量「i」 :

function sample(i) { 
    this.i = i;  
} 

sample.prototype.get_data = function() { return this.i; } 

可以按如下方式使用:

var s = new sample(42); 
alert(s.get_data()); //alerts 42 
+0

我需要添加樣品原型內塔startswith methos .. HW做針鋒相對... – Santhosh 2009-09-11 09:16:00

+3

對不起,不知道我知道你想要什麼,然後 – 2009-09-11 09:48:50

+0

沒有詢問你的幫助.. – Santhosh 2009-09-11 10:40:45

1

雖然構造函數應該以大寫字母開頭。

function Sample(i) { 
    this.i = i;  
} 

var s = new Sample(42); 
0

不知道這是多麼正確,但請試試這段代碼。它在IE中爲我工作。

添加在JavaScript文件:

String.prototype.includes = function (str) { 
    var returnValue = false; 

    if(this.indexOf(str) != -1){ 

     returnValue = true; 
    } 

    return returnValue; 
}