Is it possible to manually disrupt the predetermined prototype chain of Numbers, Strings, Booleans, and Arrays in JavaScript, or reassign values to do so?

Whenever we create a new variable of the number type (let's say num1), its __proto__ is set to point to the Number Object. The __proto__ of this points to Object Core, and its __proto__ ultimately ends with null, completing the Prototype chain.

My goal is to interrupt this chain by attempting to change the link of __proto__ from Number Object to a string. However, I have found that even after making this assignment, it still reverts back to pointing to the Object Core structure.

Am I missing something in my attempts to break the prototype chain, or is it simply not feasible to disrupt the predefined prototype chain in a browser?

Number.__proto__ = "abc"; 
let num4 = 8;
console.log(num4.__proto__); // returns Number Object
console.log(num4.__proto__.__proto__) // should return string "abc"

Output:

https://i.sstatic.net/4YyF7.png

Although, I am aware that I can add specific elements in the middle of the chain (such as within the Number-Object) using the following code:

Number.prototype.alpha = "def";
let num5 = 99; 
console.log(num5.__proto__);

Output:

https://i.sstatic.net/z2Bt1.png

Answer №1

Altering the built-in prototypes of fundamental objects, or the built-in prototype chains, is generally discouraged as it can lead to unforeseen issues. It is strongly advised not to proceed with such modifications.

Number.__proto__ represents the prototype of the Number function, and not the prototype for instances of Number (which is Number.prototype).

In JavaScript, there are both number primitives and Number objects. Typically, you interact with a number primitive. Even when using properties (including methods) on a number primitive (n = 42) like toString, the underlying mechanism references these from Number.prototype despite n being a primitive.

It is possible to modify the prototype of Number.prototype. For example, setting it to null ensures that Number objects only inherit from Number.prototype (thus breaking the connection with

Object.prototype</code)), effectively preventing property lookup on a number primitive to access properties and methods from <code>Object.prototype
:

const n = 8;
console.log(typeof n.hasOwnProperty);           // function
console.log(Object(n) instanceof Number);       // true
console.log(Object(n) instanceof Object);       // true
Object.setPrototypeOf(Number.prototype, null);
console.log(typeof n.hasOwnProperty);           // undefined
console.log(Object(n) instanceof Number);       // true
console.log(Object(n) instanceof Object);       // false

(Object(n) returns a Number object created from the number primitive n. This approach was used since instanceof always evaluates to false for primitives [n instanceof Number returns false], necessitating an object conversion for inheritance checks.)

The association between Number objects and Object has been severed in this scenario.

Once again, this act is discouraged due to its potential to cause disruptions. Just because something is feasible doesn't imply it should be done.

Nevertheless, I realize it's feasible to incorporate specific items within the chain (like in Number-Object) using the following code:

Number.prototype.alpha = "def";
let num5 = 99; 
console.log(num5.__proto__);

This action merely adds a property to Number.prototype, without actually inserting anything into the prototype chain. However, altering the prototype chain directly is achievable by changing the prototype of Number.prototype:

function Custom() {
}
// Transform `Custom.prototype` to an object whose prototype
// is equivalent to the prototype of `Number.prototype` (which by default is
// `Object.prototype`).
// (`Object.create` instantiates an object while setting its prototype
// to the specified object.)
Object.defineProperty(Custom, "prototype", {
    value: Object.create(Object.getPrototypeOf(Number.prototype)),
    writable: true,
});
Object.defineProperty(Custom.prototype, "constructor", {
    value: Custom,
    writable: true,
    configurable: true,
});
Object.defineProperty(Custom.prototype, "example", {
    value() {
        return "hi there";
    },
    writable: true,
    configurable: true,
});
Object.setPrototypeOf(Number.prototype, Custom.prototype);

const n = 8;
console.log(n.example());                 // "hi there"
console.log(Object(n) instanceof Custom); // true

A constructor function was utilized here solely to facilitate the usage of instanceof for checking inheritance; however, introducing a prototype without a constructor function is also viable. Below is the same code sans a constructor function:

const custom = Object.create(Object.getPrototypeOf(Number.prototype));
Object.defineProperty(custom, "example", {
    value() {
        return "hi there";
    },
    writable: true,
    configurable: true,
});
Object.setPrototypeOf(Number.prototype, custom);

const n = 8;
console.log(n.example()); // "hi there"


Note 1: It is best to abstain from altering the prototype of existing objects (e.g., using Object.setPrototypeOf). JavaScript engines optimize operations based on the assumption (typically valid) that an object's prototype remains constant once created. Changing the prototype disrupts these optimizations for the associated object.

Note 2: The usage of the deprecated __proto__ accessor property was intentionally avoided throughout. Instead, use Object.getPrototypeOf along with (if necessary) Object.setPrototypeOf for any new implementations. Furthermore, the usage of __proto__ would be unsuccessful for any object lacking inheritance from Object.prototype, where the feature is typically defined.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Use Angular2 to showcase the selected image as the main one when the user clicks on the

I'm working on creating a product thumbnail gallery, and I'd like the main image to be displayed when the user clicks on a thumbnail. I am using Angular for this project, although I am still learning my way around the framework. product.html &l ...

JS will reach its stopping point at the specified style.zIndex

I am currently in the process of setting up button elements. I have two scripts that correspond to different types of buttons - one script runs a simple collapse menu, while the other executes a more complex collapse by shifting depths and sliding one div ...

Unable to access JQuery Draggable method within partial view

In my partial view, I have multiple Divs that are designed to be draggable using the JQuery UI draggable library. The JQuery scripts are included in the master page, and when I view the partial view on its own, everything works fine. However, when I load ...

Text field value dynamically changes on key press update

I am currently working on the following code snippet: {% for item in app.session.get('aBasket') %} <input id="product_quantity_{{ item['product_id'] }}" class="form-control quantity" type="text" value="{{ item['product_quan ...

Sign in and view SESSION data on the current page without any need to refresh the

My website currently features a login form at the top of each page for users to input their username and password. Once the submit button is clicked, I utilize jQuery AJAX method to send the data to login.php without refreshing the page. Here, the credenti ...

When the second click triggers the loading of a JSON lot via AJAX

As a newcomer to jQuery and ajax, I am in the process of developing an application where content is loaded from a JSON file based on the navigation option selected. Here is the code snippet I've been working on: $(document).ready(functi ...

I require displaying the initial three letters of the term "basketball" and then adding dots

Just starting out with CSS and struggling with the flex property. Seems to work fine at larger sizes, but when I reduce the screen size to 320px, I run into issues... Can anyone help me display only the first three letters of "basketball ...

Tips and tricks for selecting a specific element on a webpage using jQuery

How can I modify my AJAX form submission so that only the content within a span tag with the id "message" is alerted, instead of the entire response page? $.ajax({ url: '/accounts/login/', data: $(this).serialize(), success: function(ou ...

Combining Mouseover and Click Events in Vue JS

Having four pictures, I want to display a specific component when hovering over them. However, I also need to bind the click event so that clicking on the picture will reveal the component. The challenge is that I am unable to simultaneously bind two event ...

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

No feedback received from JSON

Hi, I'm having trouble receiving JSON response using JavaScript. My goal is to display the JSON data as a treeview. index.html: <!DOCTYPE html> <html> <head> <title>JSON VIEW</title> <link href="https:// ...

When attempting to click on my subtopics using jQuery, they do not appear as expected

$(document).ready(function () { $("#subTopics").hide(); $("#mainTopics").click(function () { $("#subTopics").show("slow"); }); }); body { margin: 0; } li, a{ text-decoration: none; list-style-type: none; text-d ...

Tips for asynchronously updating a model in TypeScript

I have been working on a function to hide the element for connecting to Facebook upon successful connection. I have implemented two functions, success and error, which trigger after Firebase successfully logs in the user. While I can confirm that these fun ...

Issue with Vuetifyjs theme variable failing to function properly in version 1.0.0

Check out the step-by-step instructions provided in https://vuetifyjs.com/en/style/theme. I successfully changed the theme using the code below with vuetifyjs version 0.13.0. However, after updating to vuetifyjs 1.0.5, the font still displays correctly bu ...

"Trouble with the accordion: How to make the first one open

Is there a way to make the first tab automatically expand when the page is refreshed? I want the General tab to be expanded by default like this: General (top header) (-) lorem ipsum (-) lorem ipsum doller amu site amu doller lorem ipsum (+) lorem i ...

Vue JS: Breathing Life into Your Elements

Incorporating Vue-Router and Vuex, I have successfully implemented a Users Profile Component that fetches user information by extracting the username parameter from a router-link. For example, <router-link :to="{name: 'user', params: { usernam ...

Issues with Ionic's collection repeat functionality

I am currently iterating through an array of objects in my template and displaying them as cards using *ngfor. I want to switch to using collection repeat instead for better performance. Here is the code snippet: import { Component } from '@angular/ ...

Tips for creating animations using parent and child components in Angular

Despite my best efforts, it seems like this should be functioning properly... but unfortunately it's not... I'm attempting to achieve a transition effect on the parent element (ui-switch-groove) while the child element (ui-switch-dongle) moves. ...

Guide on how to retrieve additional data from the API by pressing the "Load More" button

Hello, I am working on a project where I aim to display user data from an API called https://reqres.in/api/users?page=(the page number can be 1,2 or more) and present it in an HTML table using JavaScript with promises. Currently, I have successfully popula ...

Enhancing JSON data in Datatables with additional text

I'm currently looking for a way to insert some text into my data before generating a table using jQuery DataTables. As an example, if my JSON data looks like [1,5,6,12], I would like it to be displayed as [1 seconds, 5 seconds, 6 seconds, 12 seconds] ...