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

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко