最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript prototype extension method - Stack Overflow

programmeradmin4浏览0评论

I have a prototype model where I need to include the following extension methods into the 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 methods or any other way to create extension methods in JS prototype model.

I have a prototype model where I need to include the following extension methods into the 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 methods or any other way to create extension methods in JS prototype model.

Share Improve this question edited Dec 24, 2015 at 15:44 Johnie Karr 2,8223 gold badges36 silver badges44 bronze badges asked Sep 11, 2009 at 9:01 SanthoshSanthosh 20.4k23 gold badges66 silver badges76 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 13

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

Constructor functions should begin with a capital letter though.

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

var s = new Sample(42);

Not sure how correct this is, but please try this code. It worked in IE for me.

Add in JavaScript file:

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

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

        returnValue = true;
    }

    return returnValue;
}
发布评论

评论列表(0)

  1. 暂无评论