Method added to Object.prototype repeats infinite timesAdding a Method to an Existing Object InstanceWhat's the difference between a method and a function?How to measure time taken by a function to executeConvert a Unix timestamp to time in JavaScriptRepeat Character N TimesPass Method as Parameter using C#Programmatically Lighten or Darken a hex color (or rgb, and blend colors)Object.prototype is Verboten?Is it not possible to stringify an Error using JSON.stringify?can't find the method I added to the external javascript library

Can a German sentence have two subjects?

cryptic clue: mammal sounds like relative consumer (8)

Is there a familial term for apples and pears?

New order #4: World

Chess with symmetric move-square

Can I make popcorn with any corn?

Showing the closure of a compact subset need not be compact

Copenhagen passport control - US citizen

Can I interfere when another PC is about to be attacked?

Download, install and reboot computer at night if needed

A function which translates a sentence to title-case

I see my dog run

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

What is the white spray-pattern residue inside these Falcon Heavy nozzles?

How do we improve the relationship with a client software team that performs poorly and is becoming less collaborative?

Patience, young "Padovan"

Where to refill my bottle in India?

Should I join an office cleaning event for free?

Is Social Media Science Fiction?

Does the radius of the Spirit Guardians spell depend on the size of the caster?

Why are 150k or 200k jobs considered good when there are 300k+ births a month?

Extreme, but not acceptable situation and I can't start the work tomorrow morning

A Journey Through Space and Time

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?



Method added to Object.prototype repeats infinite times


Adding a Method to an Existing Object InstanceWhat's the difference between a method and a function?How to measure time taken by a function to executeConvert a Unix timestamp to time in JavaScriptRepeat Character N TimesPass Method as Parameter using C#Programmatically Lighten or Darken a hex color (or rgb, and blend colors)Object.prototype is Verboten?Is it not possible to stringify an Error using JSON.stringify?can't find the method I added to the external javascript library






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I was messing around with the browser console to improve my javascript skills.



When I tried to add a method to Object.prototype, that returns its instance as json, something odd happened:



Right at the end of the method, it jumps back to the for-in loop and execute it again. Over and over again...



It does not return anything and just continues to jump back and repeat.



The code:



Object.prototype.toJSON = function() 
var tempObj = ;
for (let key in this)
if (this.hasOwnProperty(key))
let value = this[key];
tempObj[key] = value;


return JSON.stringify(tempObj);



I know you should not add methods to Object.prototype. (If I'm wrong please correct me)



This is for learning purpose only.



Can you please explain to me, why this method behaves like it does?



I don't want to know, how it would work, but why it does not work. :)



Thank you very much!










share|improve this question

















  • 4





    JSON.stringify calls toJSON if it exists on an object (which now exists on EVERY object), and you've made toJSON call JSON.stringify ... the recursion is obvious

    – Jaromanda X
    Mar 8 at 6:19












  • @JaromandaX that explains everything.. lmao Thanks alot!

    – Technikhighknee
    Mar 8 at 6:21







  • 2





    by the way, you can make it "work" by var tempObj = Object.create(null); - then tempObj is not an Object :p

    – Jaromanda X
    Mar 8 at 6:23











  • Good to know! Thanks a lot!

    – Technikhighknee
    Mar 8 at 6:33

















2















I was messing around with the browser console to improve my javascript skills.



When I tried to add a method to Object.prototype, that returns its instance as json, something odd happened:



Right at the end of the method, it jumps back to the for-in loop and execute it again. Over and over again...



It does not return anything and just continues to jump back and repeat.



The code:



Object.prototype.toJSON = function() 
var tempObj = ;
for (let key in this)
if (this.hasOwnProperty(key))
let value = this[key];
tempObj[key] = value;


return JSON.stringify(tempObj);



I know you should not add methods to Object.prototype. (If I'm wrong please correct me)



This is for learning purpose only.



Can you please explain to me, why this method behaves like it does?



I don't want to know, how it would work, but why it does not work. :)



Thank you very much!










share|improve this question

















  • 4





    JSON.stringify calls toJSON if it exists on an object (which now exists on EVERY object), and you've made toJSON call JSON.stringify ... the recursion is obvious

    – Jaromanda X
    Mar 8 at 6:19












  • @JaromandaX that explains everything.. lmao Thanks alot!

    – Technikhighknee
    Mar 8 at 6:21







  • 2





    by the way, you can make it "work" by var tempObj = Object.create(null); - then tempObj is not an Object :p

    – Jaromanda X
    Mar 8 at 6:23











  • Good to know! Thanks a lot!

    – Technikhighknee
    Mar 8 at 6:33













2












2








2








I was messing around with the browser console to improve my javascript skills.



When I tried to add a method to Object.prototype, that returns its instance as json, something odd happened:



Right at the end of the method, it jumps back to the for-in loop and execute it again. Over and over again...



It does not return anything and just continues to jump back and repeat.



The code:



Object.prototype.toJSON = function() 
var tempObj = ;
for (let key in this)
if (this.hasOwnProperty(key))
let value = this[key];
tempObj[key] = value;


return JSON.stringify(tempObj);



I know you should not add methods to Object.prototype. (If I'm wrong please correct me)



This is for learning purpose only.



Can you please explain to me, why this method behaves like it does?



I don't want to know, how it would work, but why it does not work. :)



Thank you very much!










share|improve this question














I was messing around with the browser console to improve my javascript skills.



When I tried to add a method to Object.prototype, that returns its instance as json, something odd happened:



Right at the end of the method, it jumps back to the for-in loop and execute it again. Over and over again...



It does not return anything and just continues to jump back and repeat.



The code:



Object.prototype.toJSON = function() 
var tempObj = ;
for (let key in this)
if (this.hasOwnProperty(key))
let value = this[key];
tempObj[key] = value;


return JSON.stringify(tempObj);



I know you should not add methods to Object.prototype. (If I'm wrong please correct me)



This is for learning purpose only.



Can you please explain to me, why this method behaves like it does?



I don't want to know, how it would work, but why it does not work. :)



Thank you very much!







javascript methods prototype for-in-loop






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 6:13









TechnikhighkneeTechnikhighknee

132




132







  • 4





    JSON.stringify calls toJSON if it exists on an object (which now exists on EVERY object), and you've made toJSON call JSON.stringify ... the recursion is obvious

    – Jaromanda X
    Mar 8 at 6:19












  • @JaromandaX that explains everything.. lmao Thanks alot!

    – Technikhighknee
    Mar 8 at 6:21







  • 2





    by the way, you can make it "work" by var tempObj = Object.create(null); - then tempObj is not an Object :p

    – Jaromanda X
    Mar 8 at 6:23











  • Good to know! Thanks a lot!

    – Technikhighknee
    Mar 8 at 6:33












  • 4





    JSON.stringify calls toJSON if it exists on an object (which now exists on EVERY object), and you've made toJSON call JSON.stringify ... the recursion is obvious

    – Jaromanda X
    Mar 8 at 6:19












  • @JaromandaX that explains everything.. lmao Thanks alot!

    – Technikhighknee
    Mar 8 at 6:21







  • 2





    by the way, you can make it "work" by var tempObj = Object.create(null); - then tempObj is not an Object :p

    – Jaromanda X
    Mar 8 at 6:23











  • Good to know! Thanks a lot!

    – Technikhighknee
    Mar 8 at 6:33







4




4





JSON.stringify calls toJSON if it exists on an object (which now exists on EVERY object), and you've made toJSON call JSON.stringify ... the recursion is obvious

– Jaromanda X
Mar 8 at 6:19






JSON.stringify calls toJSON if it exists on an object (which now exists on EVERY object), and you've made toJSON call JSON.stringify ... the recursion is obvious

– Jaromanda X
Mar 8 at 6:19














@JaromandaX that explains everything.. lmao Thanks alot!

– Technikhighknee
Mar 8 at 6:21






@JaromandaX that explains everything.. lmao Thanks alot!

– Technikhighknee
Mar 8 at 6:21





2




2





by the way, you can make it "work" by var tempObj = Object.create(null); - then tempObj is not an Object :p

– Jaromanda X
Mar 8 at 6:23





by the way, you can make it "work" by var tempObj = Object.create(null); - then tempObj is not an Object :p

– Jaromanda X
Mar 8 at 6:23













Good to know! Thanks a lot!

– Technikhighknee
Mar 8 at 6:33





Good to know! Thanks a lot!

– Technikhighknee
Mar 8 at 6:33












1 Answer
1






active

oldest

votes


















1














Because JSON.stringify() whill check if the object have a method toJSON, it will call toJSON if there have one.



You replace the origin toJSON to yours, and in your toJSON called JSON.stringify(), so there create a call loop.



check this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55057689%2fmethod-added-to-object-prototype-repeats-infinite-times%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Because JSON.stringify() whill check if the object have a method toJSON, it will call toJSON if there have one.



    You replace the origin toJSON to yours, and in your toJSON called JSON.stringify(), so there create a call loop.



    check this:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description






    share|improve this answer



























      1














      Because JSON.stringify() whill check if the object have a method toJSON, it will call toJSON if there have one.



      You replace the origin toJSON to yours, and in your toJSON called JSON.stringify(), so there create a call loop.



      check this:
      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description






      share|improve this answer

























        1












        1








        1







        Because JSON.stringify() whill check if the object have a method toJSON, it will call toJSON if there have one.



        You replace the origin toJSON to yours, and in your toJSON called JSON.stringify(), so there create a call loop.



        check this:
        https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description






        share|improve this answer













        Because JSON.stringify() whill check if the object have a method toJSON, it will call toJSON if there have one.



        You replace the origin toJSON to yours, and in your toJSON called JSON.stringify(), so there create a call loop.



        check this:
        https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 6:27









        Li JinyaoLi Jinyao

        169315




        169315





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55057689%2fmethod-added-to-object-prototype-repeats-infinite-times%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved