Why copy the prototype method instead of directly using it?

8

I was confused when I saw a particular javascript library code - undescore.js .

I can not remember the snippet of the code, but it was something like what I saw.

var filter = Array.prototype.filter;

var meu_array = [1, 2, 3, 4, 5, 6];

filter.call(meu_array, function (value)
{
    return value % 2 == 0;
});

That is, it copies the Array.prototype.filter method to a variable and then calls that copy with call , to set meu_array as the context of the hoot.

But, by contrast, why not do with the existing function within array directly?

meu_array.filter(function (value) {

    return value % 2 == 0;
});

Update : I copied the undescore.js source code that caused the doubt

var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
var
    push             = ArrayProto.push,
    slice            = ArrayProto.slice,
    toString         = ObjProto.toString,
    hasOwnProperty   = ObjProto.hasOwnProperty; 

Is there any special reason to do this?

    
asked by anonymous 01.08.2015 / 18:45

2 answers

3

I'm not sure, but I can assume it's to "type less" and make it easier to compress code, similar to this:

Remember that in loops if you call something like:

It will be "slow":

for (var i = 0; i < 10000; i++) {
     if (Foo.bar.test(i)) {
          //Algo escrito
     }
}

If compared to this (which is faster):

var test = Foo.bar.test;

for (var i = 0; i < 10000; i++) {
     if (test(i)) {
          //Algo escrito
     }
}

So the reasons are:

  • Write less in code
  • Better performance in execution
  • Easily compress scripts
04.08.2015 / 20:20
3

Arrays in javascript are erroneously used by some as associative arrays, which are nothing more than objects.

// versao correta
var arrAssociativo = {};
arrAssociativo.minha_chave = 'meu_valor';

// versão errada (mas também funciona na maioria dos casos)
var arrAssociativo = [];
arrAssociativo.minha_chave = 'meu_valor';

Then suppose someone uses an associative array as in the second form and do the following:

var meu_array = [];
meu_array.push = 'surpresa :)';

If you try to call the meu_array.push function you will get an error because it is now a string. However, the Array.prototype.push function is still intact.

    
04.08.2015 / 19:39