Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use JSON to create object that Inherits from Object Type?
    primarykey
    data
    text
    <p>I know how to use JSON to create objects, but there doesn't seem to be away to use JSON to create an object that is of a specific object type.</p> <p>Here's an example of an Object and creating an instance of it:</p> <pre><code>Person = function() { }; Person.prototype = { FirstName: null, GetFirstName: function() { return this.FirstName; } }; //Create an instance of the Person Object var me = new Person(); me.FirstName = "Chris"; alert(me.GetFirstName()); //alert the FirstName property </code></pre> <p>Now, I would like to use JSON to create a new Person object so that the GetFirstName function works on it.</p> <p>Here's something like that I'm looking to do (but this code doesn't work):</p> <pre><code>var you = new Person() { FirstName: "Mike" }; // OR var you = new Person{ FirstName: "Mike" }; </code></pre> <p>Is there anyway to use JSON to create an object that is of a specific type?</p> <p>UPDATE: My sample with the Person object is just to simplify the question. In fact, I am unable to modify the constructors of the actual objects that I need to create instances of. The objects are part of a third-party library.</p> <p>UPDATE: Using some of the suggestions below, I was able to figure out a way to create an object that inherits from the original, and accept JSON in it's constructor. This is neat!</p> <pre><code>personWrapper = function(obj){ for(var o in obj){ this[o] = obj[o]; } }; personWrapper.prototype = new Person(); var you = new personWrapper({FirstName: "Chris"}); alert(you.GetFirstName()); alert(you instanceof Person); // returns True - we are successfully inheriting from Person! </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload