Background
The class in javascript is something like using Prototype pattern to create objects. Objects
that instance from a class
have a common prototype, this means that these objects will contain the functions or properties of theirs prototype "object", you can regard this prototype object
as only one special object for the class.
Array
In this background, you need to understand that every array object
is a "copy" from a prototype
array object, it has all functions like forEach()
, map()
, and so on.
But this object is still an object, it is different from the prototype object, so when you use code
const myArray = ['zero', 'one', 'two'];
const myArray1 = ['three', 'four', 'five'];
myArray.myMethod = new function(){...};
myArray.myMethod();
// myArray1.myMethod(); is undefined.
It will add a new function named myMethod()
to the object myArray
, and it will only affect the object myArray
, the myArray1
does not have the function myMethod()
.
While if you use code
const myArray = ['zero', 'one', 'two'];
const myArray1 = ['three', 'four', 'five'];
Array.prototype.myMethod = function(){console.log("myMethod")};
myArray.myMethod();
myArray1.myMethod();
it will add the function myMethod()
to both myArray
and myArray1
because this time we add a function to their prototype object
.