Pregunta

Tengo un modelo de prototipo en el que necesito incluir los siguientes métodos de extensión en el prototipo:

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

Ejemplo: [JS]

sample = function() {
    this.i;
}

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

En el modelo de prototipo, ¿cómo puedo usar los métodos de extensión o cualquier otra forma de crear métodos de extensión en el modelo de prototipo JS?

¿Fue útil?

Solución

Llamando al nuevo método en cadena:

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

debería ser tan simple como:

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

Para tu segundo ejemplo, asumo que quieres un constructor que establezca la variable miembro " i " ;:

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

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

Puedes usar esto de la siguiente manera:

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

Otros consejos

Sin embargo, las funciones del constructor deben comenzar con una letra mayúscula.

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

var s = new Sample(42);

No estoy seguro de qué tan correcto es esto, pero intente este código. Funcionó en IE para mí.

Añadir en archivo JavaScript:

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

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

        returnValue = true;
    }

    return returnValue;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top