1.6 Modifying Built-in Objects

1.6 Modifying Built-in Objects

JavaScript allows us to make changes to built-in classes.
Those changes will only be active while our program runs.
As an example, say we would like to add a function to search number array sorted in ascending order:
// Don’t be concerned about how this function works Array.prototype.binarySearch = function(input) { let low = 0, hi = this.length - 1; while (low < hi) { let mid = Math.floor((low + hi)/2); if (this[mid] < input) { low++; } else if (this[mid] == input) { return mid; } else { hi--; } } return low; }
Notice how we defined the function on Array.prototype.

Extends Keyword

We can create child classes of a class. For example:
// use the extends keyword to specify that Vector is a child class of Array class class Vector extends Array { // default constructor, if no elements passed to it constructor() { } // dimen specifies how many elements in vector array constructor(dimen) { super(dimen); } // returns sqrt of sum of squares of the elements (ie. the “magnitude” of the vector) magnitude() { let sum; for (int i=0; i<this.length; i++) { sum += this[i] * this[i]; } return Math.sqrt(sum); } }
Here, Vector is the child class of Array.
In this example, Vector is meant to be an array of numbers. Vector will inherit all of the methods and properties of the Array class. However, only Vector arrays (not just any normal array) will have access to methods and properties defined in the Vector class, such as the magnitude method.

Previous Section

1.5 Predefined Objects in JavaScript
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.