Check out our Angular Book Series.

How do you override a method in JavaScript?

I'm working on an experimental project and wanted to find out if I could override a method in JavaScript. I wanted to see if I could override the JSON.stringify() method to add my own functionality. It turns out you can and it is pretty easy.

First, let's create an object we want to convert to JSON:


let myObject = {
foo: "bar",
foo2: "bar2",
foo3: "bar3"
}
console.log('------ JSON.stringify output ---------');
console.log(JSON.stringify(myObject));

Output that to make sure all is good:

Now, let's may a backup copy of JSON.stringify:


let myJSONStringifyCopy = JSON.stringify;
console.log('------ My Copy output ---------');
console.log(myJSONStringifyCopy(myObject));

This is just a new variable that references JSON.stringify() and we can use it just as we would JSON.stringify():

Okay, but now we want to replace JSON.stringify(). Create our own method:


function myOwnReplacement(value) {
return "faker";
}
JSON.stringify = myOwnReplacement;

console.log('------ JSON Stringified Replace ---------');
console.log(JSON.stringify(myObject));

console.log('------ My Copy output ---------');
console.log(myJSONStringifyCopy(myObject));

Will overwriting JSON.stringify also overwrite our myJSONSTringifyCopy? Nope as these dumps prove:

Play with the sample here.

In the case of this replacement it isn't very useful, especially since the resulting output is no longer JSON. But, I'm working on something slightly more interesting that I hope to be able to share at some future point.

Note: I do not endorse doing this to your friend's application on April Fools day, unless you really want to.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.