2009-09-11 20 views
6

Ho un modello prototipo di cui ho bisogno di includere i seguenti metodi di estensione nel prototipo:Javascript estensione prototipo metodo

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

Esempio: [JS]

sample = function() { 
    this.i; 
} 

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

Nel modello prototipo, come posso utilizzare i metodi di estensione o qualsiasi altro modo per creare metodi di estensione nel modello di prototipo JS.

risposta

13

Chiamando il nuovo metodo su stringa:

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

dovrebbe essere semplice come:

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

Per il vostro secondo esempio, suppongo che si desidera un costruttore che imposta la variabile membro "i" :

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

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

È possibile utilizzare questo come segue:

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

ho bisogno di aggiungere tha methos startswith all'interno del prototipo del campione .. hw fare tat ... – Santhosh

+3

Siamo spiacenti, non è sicuro di aver capito quello che vuoi, allora non –

+0

prob thnk 4r ur help .. – Santhosh

1

Le funzioni del costruttore dovrebbero iniziare comunque con una lettera maiuscola.

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

var s = new Sample(42); 
0

Non so quanto sia corretto, ma per favore prova questo codice. Ha funzionato in IE per me.

Aggiungere nel file JavaScript:

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

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

     returnValue = true; 
    } 

    return returnValue; 
} 
Problemi correlati