Search code examples
javascriptstringabstractionuppercasenative-code

Is there a preferred method of transferring 'intentionally generic' String or Array JavaScript methods to other objects?


In the midst of doing some debugging, I came upon a situation in which it would be preferable to generalize the toUpperCase method. Here are a few ways that I came up with:

//Local
foo = [];
foo.toUpperCase = String(foo).toUpperCase;
foo.push("a");
foo.toUpperCase();

//Global
foo = [];
window.toUpperCase = function (obj) {return String(obj).toUpperCase();}
foo.push("a");
toUpperCase(foo);

//Prototype
foo = [];
Array.prototype.toUpperCase = String.prototype.toUpperCase;
foo.push("a");
foo.toUpperCase();

//Constructor Prototype
foo = [];
Array.prototype.constructor = String.prototype.toUpperCase;
foo.push("a");
foo.constructor();

//toString override
var foo = [];
foo.push("a");
var bar = String(foo);
foo.toString = function() { return bar.toUpperCase(); }
foo.toString();

Most of the String and Array methods have this disclaimer in the spec:

Therefore, it can be transferred to other kinds of objects for use as a method.

Is there a conventional approach to implementing this type of abstraction?


Solution

  • In case you need toUpperCase function to work only with arrays then you could extend Array class like that:

    Array.prototype.toUpperCase = function () {
        return String(this).toUpperCase();
    };
    

    After that you can write:

    var foo = [];
    foo.push('a');
    foo.toUpperCase();