1

I've created 2 objects (object1 and object2) using different ways. I found no difference between them, except for the way how it is displayed in the Chrome Dev Console (see this in the below screenshot) enter image description here

var F;

function create(parent, properties) {
  F = function(p) {
    for(var i in p){
        this[i] = p[i].value;
    }
  };
  F.prototype = parent;
  return new F(properties);
}

var prop={ p: { value: 42 } };

var masterObject = {a: "masterObject value"}

var object1 = create(masterObject, prop);

var object2 = Object.create(masterObject, prop);

Following are my questions:

  1. As I'm following different ways to create objects, will there be any difference between the objects - object1 and object2?

  2. What is the difference that can be seen in the above screenshot (encircled in red)?

Temp O'rary
  • 5,366
  • 13
  • 49
  • 109

2 Answers2

1

Both Objects have the same properties, and inherit from the same object. However, theres a small difference:

new F();
//vs.
Object.create(F.prototype);

The constructor (the function called to build the object) should be different:

object1.constructor!==object2.constructor

So these objects should not be equal, however it has no real effect as the constructor is rarely used.

Should because basically

F.prototype=parent;

breaks the whole thing, as F.prototype.constructor is initialized with F , so youre overridding this. More info at Why is it necessary to set the prototype constructor?

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • I think you've missed a point, `object2` is created out of `masterObject` and not `F.prototype`. So, when I do `object1.constructor!==object2.constructor` it returns `false`. – Temp O'rary Jun 23 '17 at 14:47
  • @TempO'rary no. console.log(F.prototype===masterObj) – Jonas Wilms Jun 23 '17 at 14:48
0

When you assign a function to a variable, you created a named function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

They are functionally the same.

Andrew Burns
  • 324
  • 4
  • 10