When using the term "prototype" to refer to a Javascript method, as in "Array.prototype.foreach"?

Asked

Viewed 162 times

5

Javascript has several objects with methods, as is the case of arrays which have, for example, the method forEach.

But eventually the same name can be used by other objects, such as method forEach of NodeList. In cases such as this, the distinction is necessary to specify the manufacturer (Array and NodeList, for example) somewhere in the "full name".

So, from the semantic point of view of language, what is the correct way to use this "full name"?

  • Array.prototype.forEach?
  • Array.forEach?

If they are different, is there a correct situation to use each of these situations? Or are the two "equivalent" and refer to the same thing?

2 answers

1


In this answer, I will use the examples Array.prototype.forEach and Array.from (didn’t use Array.forEach because it does not exist). However, the same holds true for any other constructor function (apart from Array) or other property (in addition to forEach).


TL; DR

  • <constructor>.prototype.<method> should be used to refer to "instance methods". For example, Array.prototype.forEach.

  • <constructor>.<method> shall be used to refer to "static methods". For example, Array.from.

Are different.


In Javascript, every function has a property called prototype, which is always an object (or null). In the case of the function Array, the property prototype is an object that contains several properties and methods, such as map, filter, reduce, etc. Looks familiar, right?

When a function can be invoked using the operator new, it can also be called the constructor function. So when a new object is created from of a construction function, the internal property [[Prototype]] of this new created object points to the property prototype of the construction function.

For example, how Array is a function constructor, I can build a new object array like this:

const arr = new Array();
// `arr.[[Prototype]]` aponta para `Array.prototype`

// Podemos então, acessar, a partir do objeto construído,
// os métodos da propriedade `prototype` da função construtora,
// isto é, `arr.[[Prototype]]` aponta para `Array.prototype`.
typeof arr.map; // 'function'
typeof arr.filter; // 'function'
typeof arr.reduce; // 'function'

Thus, thanks to the prototyping chain, all methods of Array.prototype will be available in arr. To better understand, read the answers from How prototypes work in Javascript? and of What is a Javascript Prototype?.

We can therefore conclude that:

  • Array.prototype.forEach

    The nomenclature to be used to refer to a method (in this case forEach) available at the property prototype of a construction function (such as Array). In the face of the Javascript prototyping chain, the method forEach can be accessed as property of any object built from the consttutor function Array.

    In other words, we can use a nomenclature like Array.prototype.forEach to refer to the methods available in the "instances" of Array.

  • Array.from

    Is the nomenclature to be used to reference a property of the constructor function Array. As it is not part of Array.prototype, is not passed to the "instances" of Array. It can be said that it is the nomenclature to be used by "static methods".


Some examples:

// `arr` é como se fosse uma "instância" de `Array`:
const arr = new Array();

console.log(typeof Array.map); // 'undefined'
console.log(typeof Array.from); // 'function'

console.log('---');

console.log(typeof Array.prototype.map); // 'function'
console.log(typeof Array.prototype.from); // 'undefined'

console.log('---');

console.log(typeof arr.map); // 'function'
console.log(typeof arr.from); // 'undefined'

Note in the above example that, if unmodified, arr "will inherit" all the properties of Array.prototype. The reason for this was at the beginning of this answer.

Also note that although available as property of the constructor function Array, the "static method" Array.from nay is accessible from Array.prototype or of arr (the "instance").

Also know that (for example above):

  • arr.forEach is the same as Array.prototype.forEach;
  • [].forEach is the same as Array.prototype.forEach;

However, it is more convenient to use Array.prototype.forEach than arr.forEach, since the latter depends on the variable name (in this case, arr).

[].forEach is also valid, but only because [] is a literal form of Javascript that will always refer to an array object built from Array.

In short, the standard <constructor>.prototype.<method> is always guaranteed to refer to methods present in objects constructed from <constructor>.

0

They are different. Array.prototype.forEach allows you to access the constructor function of Array.forEach.

console.log(Array.forEach) // undefined
console.log(Array.prototype.forEach) // function forEach() { [native code] }

This way you can even modify the behavior of forEach.

let lista = ["Um", "dois"]

const inverter = function () {
  return lista.reverse()
}

// Aqui acesso o protótipo do forEach
Array.prototype.forEach = inverter


console.log(lista) // ["Um","dois"]
console.log(lista.forEach()) // ["dois", "Um"]

In short you use Array.forEach when you want to access the object and Array.prototype.forEach for the prototype of the object.

  • 3

    As well, "function constructing the forEach”?

  • I have separated two things for the answer to your question, https://developer.mozilla.org/en-US/docs/Glossario/Prototype and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor... In the JS I believe most native functions, when you find them[Native code] in a return, she is a class... Another issue is that @Thyago Dias showed you an example because it is not recommended to change native functions for the sake of generating internal errors unless you know what you are doing.

  • 2

    Thyago, I still couldn’t understand what you meant by "[...] constructor function Array.forEach". Could you please try to clarify?

  • A constructor is nothing more than a function, i.e., constructor function is a structure that describes states and behaviors of an object. A class can be considered a constructor function

Browser other questions tagged

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