Why copy the prototype method instead of using directly?

Asked

Viewed 157 times

8

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

I don’t really remember the code part, 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 method Array.prototype.filter for a variable and then calls that copy with call, to define meu_array as part of the.

But, on the other hand, why not do with the function existing within the array directly?

meu_array.filter(function (value) {

    return value % 2 == 0;
});

Updating: I found a passage from 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?

2 answers

3

Javascript arrays 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';

So suppose someone uses an associative array as in the second form and does the following:

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

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

3


I’m not sure, but I can assume it’s to "type less" and facilitate the compression of code, similar to this situation:

Remembering that in loops we call something like:

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
  • Facilitate the compression of scripts

Browser other questions tagged

You are not signed in. Login or sign up in order to post.