Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Last active August 2, 2023 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vxhviet/44b8db496ef2de6bad136b7548df4c3a to your computer and use it in GitHub Desktop.
Save vxhviet/44b8db496ef2de6bad136b7548df4c3a to your computer and use it in GitHub Desktop.

[JavaScript] - Prototypal Inheritance on Built-In Objects

const Person = function (firstName, birthYear) {
  this.firstName = firstName; // assign param to `this.firstName` property
  this.birthYear = birthYear;
};
const jonas = new Person('Jonas', 1991);

console.log(jonas.__proto__);
// Object.prototype (top of prototype chain)
console.log(jonas.__proto__.__proto__); // Object.prototype
console.log(jonas.__proto__.__proto__.__proto__); // null

console.dir(Person.prototype.constructor);

const arr = [3, 6, 6, 5, 6, 9, 9]; // new Array === []
console.log(arr.__proto__);
console.log(arr.__proto__ === Array.prototype);

console.log(arr.__proto__.__proto__); // Object.prototype

// add new function to Array.prototype
Array.prototype.unique = function () {
  return [...new Set(this)];
};

console.log(arr.unique());
// However, this is a bad practice, don't do this as:
// 1. the next version of JS might add a method with the same name with a different behavior
// 2. big team with multiple developers might accidentally create multiple methods with the same name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment