Home > Blockchain >  JavaScript - Confusion between global classes and inheritance
JavaScript - Confusion between global classes and inheritance

Time:12-30

Total begginer who learns JS here. I don't understand why when you declare a variable it doesn't TOTALLY inherit of it's parent class methods, for e.g.:

// I initiate an array (my question is the same for all type of vars)
var myArr = ["foo", "bar"]

// Let's say I call a random function of the parent class Array
console.log(Array.isArray(myArr)); // true

// Since I assume that myArr inherited of the COMPLETE LIST of Array's methods, I should be able to do this:
console.log(myArr.isArray()); // Uncaught TypeError

Why don't the variables inherit of all of the methods of it's parent classes? Instead of that you need to mix between the fonctions of Array and myArr. They should be identitical on the two sides, no?

CodePudding user response:

Array.isArray can also be called on non-arrays, so calling it from the instance of other classes would not have the method, resulting in a runtime error. Basically if you knew it was an array and it would be callable, you would not need to call it.

That is why it is NOT on the Array prototype and NOT callable from the instance.

const a = null
a.isArray() // bad
Array.isArray(a) // good

Developers have the option in Javascript to add methods to the class, the instance (aka prototype), or both. In this case it was only added to the class, not the instance.

It could have been added to the prototype of Object, but then it still would not be on the instances of boolean, number, string, symbol, or undefined.

CodePudding user response:

When you declare a variable it is an instance of a Class, there is not inheritance.

When you declare a class that extends another class is where inheritance occurs.

Array.isArray() is a static property of the JavaScript Array object.

Usually, static methods are used to implement functions that belong to the class, but not to any particular object of it.

CodePudding user response:

You need to pass an array as a parameter to the isArray function.
Eg:

console.log(myArr.isArray(myArr))
  • Related