What is the best way to transfer functions connected to an Object over to Object.prototype?

Imagine having this:

var exampleObject = {age: 25, name: 'John'};

If you do this:

Object.keys(exampleObject); // it will return ['age', 'name']

Now, what if you want to add this functionality to the object prototype? You can achieve it like so:

Object.prototype.getKeys = function(){ 
    return Object.keys(this);
};
exampleObject.getKeys(); // returns ['age', 'name']

Next objective: Let's take all functions associated with the Object and incorporate them into the prototype. Here's how I approached it:


Object.getOwnPropertyNames(Object)
    .filter(function(element){ 
        return Object[element] && Object[element].constructor.name === "Function";
    })
    .forEach(function(functionName){ 
        Object.prototype[functionName] = function(){
            return Object[functionName].apply(this, Array.prototype.slice.call(arguments, 1));
        };
    });

Essentially, we are retrieving all functions linked to the Object, then looping through to attach them to the prototype.

However, when trying exampleObject.getKeys(), an error pops up stating

TypeError: Object.keys called on non-object
.

Can anyone spot the mistake here?

Answer №1

Using apply() with Object.keys is not the correct approach in this situation.

Object.prototype.keys = function(){

    {b:2,c:3}.keys(Array.prototype.slice.call(arguments,1))
    // ^^ or whatever "this" is when you call .apply(this, arguments)
}

The solution is to simply call Object.keys without manipulating the this value within the function. The code should look like this:

Object.getOwnPropertyNames(Object)
    .filter(function(e){return Object[e] && Object[e].constructor.name==="Function"})
    .forEach(function(funcName){ 
        Object.prototype[funcName]=function(){
            return Object[funcName](this);
        }
    });

However, it's generally advised against adding new methods to native prototypes like this.

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

Combining plugin setups and functionalities into a unified script

When it comes to grouping plugin initializations and scripts in a website, I often have a "tools.js" file that contains various functions, click events, and more. I prefer keeping all these script calls centralized in one file for simplicity, organization, ...

What is the best way to have a button activate a file input when onChange in a React application?

Having an input field of file type that doesn't allow changing the value attribute and looks unattractive, I replaced it with a button. Now, I need the button to trigger the input file upon clicking. How can this be achieved in React? Edit: The butto ...

Divide JSON information into distinct pieces utilizing JQuery

$.ajax({ type: 'POST', url: 'url', data: val, async: false, dataType: 'json', success: function (max) { console.log(max.origin); } ...

How can one break down enum values in typescript?

I've defined an enum in TypeScript as shown below: export enum XMPPElementName { state = "state", presence = "presence", iq = "iq", unreadCount = "uc", otherUserUnreadCount = "ouc", sequenc ...

How can I attach a click event to the left border of a div using jQuery?

I am wondering about a div element <div id="preview"> </div> Can anyone suggest a method to attach a click event specifically to the left border of this div? Your help is greatly appreciated. ...

Retrieving a property of an object within a function

I'm facing an issue where I am trying to access the properties of objects inside an array in my code to display text values in input boxes that are recovered from local storage after a refresh. However, when I attempt to run a for loop within my appSt ...

Creating a responsive design for mobile apps in Ionic using CSS

I need help with making my Ionic app responsive across all mobile devices. The design on the page was created using CSS, but it is not displaying properly on every device. How can I ensure that it adapts to different screen sizes? <template> <Io ...

Updating a JSON property in JavaScript on the fly

I am looking to dynamically replace the content of "placeholder" with {"John": "Dough"} using a function call. This initial method seems to work fine: a = {foo:{bar:{baz:"placeholder"}}}; a.foo.bar.baz = {"John" : "Dough"}; console.log(JSON.stringify(a)) ...

Upon clicking, the reset function will be triggered

I have a jQuery code that includes a click event on td elements. After clicking on a td, an input field with text appears and the focus is set at the end of the text. However, I want to remove the focus after the initial click so that I can click in the ...

What is the method in JavaScript for a child function to trigger a Return statement in its parent function?

I have encountered a unique problem. I need to retrieve some data downloaded via ajax and return it, but neither async nor sync modes are fetching the data in time for the return. Is there a way to call the return from a child function to the parent func ...

Identifying the Source of a Page Redirection in Javascript: A Step-by-Step Guide

After downloading a free template from the internet, I noticed that there was a link back to the website in the footer. Upon attempting to remove this link, my page started redirecting to the homepage URL of the original website. How can I pinpoint which ...

Oops! Remember to always `await server.start()` first before using `server.createHandler()` in next.js

An error is popping up when I attempt to check the functionality of Apollo GraphQL. Error: You must await server.start() before calling server.createHandler() Note: Although there is a similar question regarding this issue, it is specific to Express. Error ...

Encountering an Error in Node.js When Defining Routes Using Variable Routes

Here is the code snippet from my App.js file- var routes = require('./routes'); app.get('/', routes.index); //var abt = require('./routes/about'); app.get('/about', routes.about); This is the code from my index.j ...

Using VueJS to dynamically manipulate URL parameters with v-model

Hello, I am new to coding. I am working on calling an API where I need to adjust parts of the querystring for different results. To explain briefly: <template> <div> <input type="text" v-model="param" /> ...

Shifting JSON Arrays in JavaScript - Changing Order with Ease

Consider the following JSON data: [ { "name": "Lily", "value": 50 }, { "name": "Sophia", "value": 500 }, { "name": "Ethan", "value": 75 } ] I am looking to verify and organize it in ...

Tips for capturing all mobile events in Angular

Trying to capture all mobile events like touch and swipe, I have added event listeners at the document level: document.addEventListener('tap', trackTouchActivity, false); document.addEventListener('swipe', trackTouchActivity, false ...

Issues with displaying HTML5 audio player in iOS Chrome and Safari browsers

My html5/jquery/php audio player is working well on desktop browsers, but when I tried testing it on iOS, all I could see was a grey track bar. I suspect that the controls are hidden behind the track bar because sometimes the associated file starts playing ...

List of random points generated using Three.js

Novice inquiry: I have generated some random points in JavaScript. How can I individually access each point later on? I remember something about an 'Object' that holds all the points, allowing me to manipulate their positions or selectively retri ...

The Splitter remains inactive until a peculiar series of actions is taken

Trying to troubleshoot this issue with a library called Split.js, which can be found here: https://github.com/nathancahill/Split.js I've encountered an interesting problem where I have to disable the height CSS property of my container, move the spli ...

Pictures in the portfolio failing to load on Mozilla Firefox

Having some trouble with my WordPress website bmfconstruction.com.au/new/. In the project section, all images are loading correctly in Chrome, Opera, and IE. However, when it comes to Firefox, none of the images seem to be showing up. I've tested this ...