Search code examples
javascriptjqueryjsonobjectstringify

two ways of creating object in javascript


I'm creating javascript object by doing something like:

function field(name,label){
        this.name = name
        this.label= label;
}

var a = new field("market","Mkt").

Then I assign a to another object.

object.newField = a;

The second way of doing it is to create a new property directly

object.2ndNewField = {
    name: "market2",
    label:"Mkt2"
}

I try to read the objects in other functions. They behave differently, however, when i stringify the object, it looks ok. What's the difference between the two properties i created?

btw is there any difference of the following object?

 object.2ndNewField = {
        "name": "market2",
        "label":"Mkt2
    }

Solution

  • The difference is that in the first case, the created object inherits from field.prototype then Object.prototype (i.e. its internal [[Prototype]] is field.prototype, whose internal [[Prototype]] is Object.prototype), where as in the second case it inherits only from Object.prototype.

    Another way to look at it is:

    object.newField instanceof field; // true
    object.newField instanceof Object; // true
    
    object.newField2 instanceof field; // false
    object.newField2 instanceof Object; // true
    

    or the inheritance chains are:

    object.newField  -> field.prototype -> Object.prototype -> null
    
    object.newField2 -> Object.prototype -> null
    

    where '->' means "inherits from".