0

I saw below code on developer.mozilla.org can anyone, please tell me how myArray.myMethod will work?

const myArray = ['zero', 'one', 'two'];
myArray.myMethod = function (sProperty) {
    console.log(arguments.length > 0 ? this[sProperty] : this);
};

myArray.myMethod(); // prints "zero,one,two"
myArray.myMethod(1); // prints "one"
  • 1
    If you've seen that on MDN then there will be an explanation anywhere on that same site. Also... If `myMethod` was a method on the prototype of `Array` it would be available on any array and not only on `myArray`. Should be easy to test. – Andreas Sep 07 '21 at 08:38
  • [Related](https://stackoverflow.com/questions/572897/how-does-javascript-prototype-work). – Teemu Sep 07 '21 at 08:52
  • Where exactly did you see this code on MDN? Please link the page. – Bergi Sep 07 '21 at 09:05
  • No, it's not a prototype, or a prototype method – Bergi Sep 07 '21 at 09:06
  • https://developer.mozilla.org/en-US/docs/Web/API/setTimeout – Deepak Gupta Sep 07 '21 at 09:17

1 Answers1

0

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.

Bob Zhang
  • 27
  • 8