Customizing window.alert to accept more than one argument

I am wondering about customizing the window.alert function in order to pass multiple parameters.

Can anyone offer an explanation as to why the for/in loop inherits the body of Array.prototype.tester into the list array?

Your insight is greatly appreciated.

Array.prototype.tester = function() {
    return 'tester';
}

window.alert = function() {
    var args = Array.prototype.slice.call(arguments);
    var list = [];

    for (var i in args) {
        list.push(args[i]);
    }

    return list.join(', '); // WHY???? alerts: "arg1, arg2, function () { return "tester"; }"
    //return args.join(', '); // alerts: "arg1, arg2" expected.
}

alert('arg1', 'arg2');

Answer №1

for-in loops through all enumerable properties of an object, capturing those defined in the object or its prototypes. Many pre-installed functions are marked as non-enumerable, so they do not show up during regular iteration. With ECMAScript 5, it is possible to designate your own properties as non-enumerable, though browser compatibility may vary:

function exampleFunction() {
  return 'example';
}

Object.defineProperty(Array.prototype, 'example', {
  value: exampleFunction,
  writable: true,
  enumerable: false,
  configurable: true
});

Answer №2

In a helpful comment from breakingbad, it was pointed out that the for in loop iterates over properties defined by yourself that are in the objects prototype chain.

To resolve this issue, utilize the hasOwnProperty() method.

for (var i in args) {
    if (args.hasOwnProperty(i)) {
        list.push(args[i]);
    }
}

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

Utilizing Cordova and AngularJS to efficiently retrieve JSON data through XMLHttpRequest in a factory

I've encountered an issue while attempting to retrieve a JSON from an API using XMLHttpRequest within a factory. Despite the debug logs suggesting that everything is functioning correctly, I keep getting an "undefined" response. Below is the code for ...

What scenarios call for the utilization of setScriptTimeout?

When using Selenium WebDriver, there is a method called setScriptTimeout(time, unit). The description of this method states that it Specifies the time allowed for an asynchronous script to finish executing before an error is thrown. If the timeout is set ...

What is causing the beforeUpdate hook in Sequelize to fail?

I have a user model with 2 hooks that I am working on. User.beforeCreate(setSaltAndPass) User.beforeUpdate(setSaltAndPass) The first hook works perfectly fine, but the beforeUpdate hook is not triggering as expected. As per the documentation, there should ...

Creating numerous Facebook posts using jQuery technology

I am currently facing a challenge when attempting to publish multiple facebook posts on a webpage using jQuery. Although I have managed to successfully post the first facebook post, I am encountering difficulties when trying to post another one. What coul ...

Is there a way to modify the browser's user agent using JavaScript or HTML?

I currently have an application that is running on IE7. However, an analytics tool I rely on has recently been updated and now requires a minimum of IE8. Is there a way to modify the User Agent in IE7 using JavaScript or HTML to trick it into being recogni ...

Only initiate an AJAX call if there are no other pending AJAX requests from prior function invocations

Arriving at a new, chaotic code base with no testing available has presented me with a significant challenge. I am currently struggling to resolve an issue without the use of ES6, only relying on plain vanilla JS and jQuery. The scenario: Within a web pag ...

Obtain the value or values of radio buttons based on certain conditions

Recently, I have been delving into .JS and grappling with pre-existing code. One of the challenges I face involves extracting data from radio buttons after a particular selection is made. The gist of it is related to transportation requirements. Upon indi ...

What is the process for executing PhantomJS commands through a NodeJs server?

My current challenge involves setting up a Node Server and incorporating PhantomJS commands within the NodeJS server. An example command includes: phantomjs phantom-server.js http://example.com Although I found some information related to this issue on ...

Validating the length of digits in an Angular JS number input - tips and tricks

Our goal is to create an input field that only allows values from 0 to 24 (for a time entry application). These are the specific values users should be able to input: 0 1 2 3 4 5 6 7 8 9 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 2 ...

In JavaScript coding language, you can use this syntax to create an array and push the

When the variable foo is defined, why does the following code behave in a certain way? var array = [].push(foo); When executed, why does the output equal 1? Based on my testing, the variable array simply returns the length of the array. Therefore, if ...

Echarts: scatter plots linked with a line to the axis (resembling the PACF diagram)

I am currently working with echarts (js). Is there a method to link the dot of the scatter plot with the 0 value on the y-axis? I want it to resemble a pacf plot, similar to this example: The desired outcome should look something like this: https://i.sta ...

JavaScript and PHP are successfully displaying a success message despite the data not being saved to the database

I recently added a new feature to my website where users can submit a form using Javascript without having to reload or refresh the page. This allows for a seamless experience and displays success messages instantly. However, being a newcomer to Javascript ...

Tips for clearing out text in a <p> tag with javascript when it exceeds a specific length of 100 characters

Is there a way to automatically truncate text to (...) when it exceeds 100 characters inside a paragraph with the class .class? For instance, if I have a long paragraph like this: <div class='classname'> <p>Lorem ipsum dolor sit ame ...

Having trouble adding a div in React due to the error "Objects are not allowed as a React child"?

While I am rendering the data and displaying it between divs, I keep getting this error: Objects are not valid as a React child (found: Wed Dec 09 1998 00:00:00 GMT+0530 (India Standard Time)). If you meant to render a collection of children, use an ...

Tips for customizing the appearance of buttons in a JavaScript bxSlider

Take a look at my landing page: In the upper section, you'll find three buttons that allow you to switch between different slides. These buttons are named: credi5, credi10, and credi15. Now, I want to replace those buttons with images... specificall ...

troubleshoot using Visual Studio Code

Here's the scenario: I need to debug a project using VS Code. The project is usually started by a batch file and then runs some JavaScript code. Now, I want to debug the JavaScript code, but I'm not sure how to do that. If anyone has any instruct ...

Disabling the loading of JavaScript on a Magento website

Seeking advice - I'm experiencing a delay on my website due to 3 unnecessary javascripts that are being loaded. Is there a way to prevent these scripts from loading or being searched for? Listed below is the website log where I am unable to locate jq ...

Using ReactJS to pass an object as an argument instead of a function in the

As a newcomer to React, I am still in the process of learning the MVC pattern and all things related to it. Currently, I am following the examples provided on the React homepage and trying to expand upon them. However, I have encountered an issue when atte ...

Interactive element for initiating a HTTP request to NodeJS/Express server to trigger a specific function

I currently have a frontend button implemented using nodejs and express for my server-side backend. The button is supposed to trigger a function that controls the Philips Hue API on the backend via an HTTP request. I have experimented with various approac ...

Alert box in Vue.js

Embarking on my journey with VueJS. I previously implemented an alert box using jQuery. Now, I am attempting to recreate that in VueJS. Here is my current progress: 1- Developed a component named NovinAlert.vue which includes: <template> & ...