views:

253

answers:

2

i'm having a prototype model where i need to include the following extension methods into prototype.

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

Example: [JS]

sample = function(){
this.i;
}

sample.prototype = {

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

}

In the prototype model how can i use the extension mehods or any other way to create extension methods in JS prototype model.

+1  A: 

Calling the new method on string:

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

should be as simple as:

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

For your second example, I assume you want a constructor that sets the member variable "i":

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

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

You can use this as follows:

var s = new sample(42);
alert(s.get_data()); //alerts 42
Jonas H
i need to add tha startswith methos inside the sample prototype..hw to do tat...
santose
Sorry, not sure I understand what you want then
Jonas H
no prob thnk 4r ur help..
santose
+2  A: 

Constructor functions should begin with a capital letter though.

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

var s = new Sample(42);
Alex