User Tools

Site Tools


notes:javascript:extending_javascript_types

Extending the Built-in JavaScript Types

Examples of extending the Array type:

Array.prototype.indexOf = function(o) {
    for(var i=0; i<this.length; i++) {
        if(this[i]==o)
        return i;
    }
    return -1;
};
 
Array.prototype.lastIndexOf = function(o) {
    for(var i=this.length-1; i>=0; i--) {
        if(this[i]==o)
        return i;
    }
    return -1;
};
 
Array.prototype.contains = function(o) {
    return this.indexOf(o) != -1;
};
 
Array.prototype.copy = function(o) {
    return this.concat();
};
 
Array.prototype.insertAt = function(o,i) {
    this.splice(i,0,o);
};
 
Array.prototype.insertBefore = function(o,o2) {
    var i=this.indexOf(o2);
 
    if(i == -1)
        this.push(o);
    else
        this.splice(i,0,o);
};
 
Array.prototype.removeAt = function(i) {
    this.splice(i,1);
};
 
Array.prototype.remove = function(o) {
    var i=this.indexOf(o);
 
    if( i!= -1 )
        this.splice(i,1);
};

Examples of extending the String type:

String.prototype.endsWith = function (suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
 
// Check if the startsWith method already exists.
if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
};
notes/javascript/extending_javascript_types.txt · Last modified: 2020/08/26 (external edit)