Site icon i2tutorials

Javascript-Built-in Classes

Javascript-Built-in Classes

 

Built-in classes are like Array, Map, and others are extendable also.

PowerArray inherits from the native Array:

 

// add one more method to it (can do more)
class PowerArray extends Array {
 isEmpty() {
   return this.length === 0;
 }
}

let arr = new PowerArray(1, 2, 5, 10, 50);
alert(arr.isEmpty()); // false

let filteredArr = arr.filter(item => item >= 10);
alert(filteredArr); // 10, 50
alert(filteredArr.isEmpty()); // false

 

Built-in class methods like filter, map, and others – call new objects of exactly the inherited type PowerArray. Their internal implementation provides the object’s constructor property for that.

 

arr.constructor === PowerArray

 

When arr.filter() is called, it internally generated the new array of results using exactly arr.constructor, not basic Array. That is actually very cool because we can keep using PowerArray methods further on the result.

 

Even more, we can customize that behavior.

 

you can add a special static getter Symbol.species to the class. If it exists, it should call the constructor that JavaScript will use internally to provide new entities in the map, filter, and so on.

 

If we’d like built-in class methods like map or filter to call a regular array, we can return Array in Symbol.species, like here:

 

class PowerArray extends Array {
 isEmpty() {
   return this.length === 0;
 }

 // built-in methods will use this as the constructor
 static get [Symbol.species]() {
  return Array;
 }
}

let arr = new PowerArray(1, 2, 5, 10, 50);
alert(arr.isEmpty()); // false

// filter creates new array using arr.constructor[Symbol.species] as constructor
let filteredArr = arr.filter(item => item >= 10);

// filteredArr is not PowerArray, but Array
alert(filteredArr.isEmpty()); // Error: filteredArr.isEmpty is not a function

 

now .filter returns Array. The extended functionality is not passed any further.

Built-in objects have their own static scopes, for instance, Object.keys, Array.isArray etc.

Native classes extend each other. For instance, Array extends Object.

Normally, when one class extends another. Both static and non-static methods are inherited.

But built-in classes are an exception. They do not inherit statics from each other.

 

Exit mobile version