Replace default global variables in contemporary web browsers

After reading the John Resig article on overriding globals in the browser, I attempted to replicate the code in my own browser. However, to my surprise, nothing happened when I ran the example.

Here is the code snippet:

var sec = {};
function Array() { 
    alert(1); 
    sec = this; 
}; 

Even when I executed ["zdxc", "sd", 1111, 11.1] in the browser console, no alert was displayed and it seemed like the Array declaration had no effect.

I'm wondering if this issue has been fixed in modern browsers or if it still works in certain versions of browsers. Any insights?

Answer №1

It's happening because you're overriding the Array constructor, which causes the new Array(); call to return your custom object instead of a true Array.

For example, when you do:

var arr = ["zdxc", "sd", 1111, 11.1];

the variable arr becomes a native Array.

But if you do:

var arr_override = new Array();

then arr_override becomes an Object as per your constructor declaration, triggering the alert statement. By overriding the constructor, the identifier loses its Array initialization and assumes the behavior defined by your custom function.

As mentioned in this answer on Stack Overflow, the Array Literal ([]) hasn't been affected by this since around 2008 in major browsers.

EDIT:

After some experimentation, it seems that modifying the behavior of the [] notation is not possible, nor is it recommended to alter Native Objects (especially their constructors). However, extending prototypes and tweaking existing properties/methods like demonstrated below is feasible:

var arr = [];
arr.push('2323');
alert(arr);

Array.prototype.push = function() { alert('trololololo'); }
arr.push(123);

I hope this clarifies things. Cheers!

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

Using Regular Expressions to Replace in a JSON Format

I am currently attempting to perform a Regex Replace on a JSON string that resembles the following: String input = "{\"`####`Answer_Options11\": \"monkey22\",\"`####`Answer_Options\": \"monkey\",\"Answer_Option ...

Possible revision: "Exploring ways to iterate through an array of objects in Node/Express and verify if a corresponding entry exists in a MongoDB

Working on building a web application using the MEAN stack and Yelp API to retrieve an array of objects representing local businesses. I manipulate this data on the front-end, but before sending a response, I need to verify if a specific object exists in m ...

How is it possible for this variable to be altered without any modifications made to it in the current function?

This particular function receives two arrays as input: arrOne, which is an array comprising arrays of numbers, and arrTwo, which is an array containing numbers. My goal here is to generate every possible combination, followed by obtaining the unique combin ...

"Using Vue 3 to teleport content to a specific element and swap out existing

I've successfully implemented the use of Vue 3 teleport to display elements within a div. Although teleport adds items to the specified element, it doesn't replace existing elements in the div. Is there a way to configure teleport to replace th ...

Encountering an issue upon launching a new next.js project

Upon setting up my next.js project and running it, I encountered the following error: Error - ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[1]!./node_modules/next/dist/build/webpack/loaders/postc ...

Combining multiple arrays into a single array using JavaScript

Forgive my beginner question, but I am just starting to learn JavaScript and I can't shake this thought. Let's use an example: Suppose we have: animals['Cat', 'Dog']; and, mood['Sad' , 'Happy']; I ne ...

What is the method for invoking a function with a chosen date in the @syncfusion schedule with Angular 9?

capture of calendar display I am looking for a way to trigger a function with the selected date as a parameter. However, I am unable to locate the appropriate event to use within this module. Can someone provide assistance with this issue? Thanks! ...

How to structure JSON data in Python

I have a file (C:\data.txt) containing JSON objects with millions of records. Here is an example record: 1 123-567-9876 TEST1 TEST 717-567-9876 Harrisburg null US_PA I want to extract only the data from my notepad, without parentheses, etc. Once I cl ...

How come I am getting only a single outcome when iterating through a dataset array?

I have a fetch API that returns an array of objects, and within those objects are nested arrays and other objects. My goal is to filter out only the objects that contain a specific value. Specifically, I want to retrieve objects with an id of 11 from the p ...

Using a JavaScript variable in a script source is a common practice to dynamically reference

I have a scenario where an ajax call is made to retrieve json data, and I need to extract a value from the json to add into a script src tag. $.ajax({ url: "some url", success: function(data,response){ console.log("inside sucess"); ...

How should res.render() and res.redirect() be properly utilized within Express framework?

I am struggling to understand the difference between res.render('viewname', {msg: 'Message' }) and res.redirect('route') The render function allows you to pass a "message", but the redirect function does not. However, ther ...

AngularJS remove a row from a table disrupts the formatting

Hello! I am attempting to delete rows from a table in Angular. I want the first two rows to have a red background and the rest to have a white background. If I try to delete the last row, it gets deleted but the color remains for the first row only (it sh ...

Placing a div on top of a link renders the link unusable

I am facing a situation and require assistance (related to HTML/CSS/JS) I currently have a div containing an image (occupying the entire div space) such that when hovered over, another div with an image is displayed on top (the second div is semi-transpar ...

Error encountered when referencing iscrollview and iscroll js

Greetings! I am new to the world of JavaScript and jQuery, currently working on developing a phonegap application. As part of my project, I am exploring the implementation of the pull-to-refresh feature using iscroll and iscrollview as demonstrated on & ...

JavaScript encountered a runtime error due to a script error: The object does not have support for the property or method 'row' when using the datatables plugin

Currently, I am utilizing the datatables plugin for my application which can be found at the following link: https://datatables.net/examples/api/row_details.html After clicking on a row in the table, I encountered the error message below. I am having dif ...

Click on the event to save the document and print the HTML page

Is there a way to create an onclick event that saves the current HTML page as a document and then prints it? <html> <body> <div class="reportformat"> <div class="format1"> <table> <tr ...

updating a d3js line graph in real-time using JSON information

Trying to wrap my head around dynamically updating a line graph with new data, shifting the graph to the left and adding fresh data from the right - you following me? Want it to behave just like the examples on I'm fairly new to d3 (javascript) and l ...

What is the functionality of the getBlock('meta') method within DocPad?

While transitioning a website from a different site generator to DocPad, I am currently exploring the capabilities of the getBlock('meta') feature. Understanding how to utilize getBlock('scripts') and getBlock('styles') was re ...

`What is the best way to assign values to an array using data from a JSON file?`

In order to enhance productivity and organization among my peers, I am currently in the process of developing a groundbreaking SwiftUI application for iOS. The main focus of this app is to assist us in managing our academic assignments effectively. To ens ...

Save a JSON-formatted string as a JSON file

I have a string in JSON format that looks like this: arbre={"name":"flare","children":[{"name":"Algèbre","children":[{"name":"Nombres Fractionnels","children":[{"name":"Addition fractionnelle","size":8.333333333333334}, {"name":"Division fractio ...