Search code examples
javascriptprototypeprototypejs

Javascript assigning prototype confusion


var object1 = {
    name: "abc",
    age: 21
}

var Object2 = function() {}
Object2.prototype = object1;
Object2.prototype.hello = function() {
    console.log("Hello");
}

var obj = Object.create(object1);
for (var prop in obj) {
    console.log(prop + ": " + obj[prop]);
}

The output of this code is:

name: abc
age: 21
hello: function () {
    console.log("Hello");
}

Obj is created by setting its prototype as object1, which doesn't have the 'hello' function, so why is it listed in the output? If I comment out 'Object2.prototype = object1;', the 'hello' function no longer shows in the output. I don't see how obj and Object2 are connected. Can anyone please explain what's happening here?


Solution

  • After this line...

    Object2.prototype = object1;
    

    ... both Object2.prototype and object1 refer to the same object. Hence this line...

    Object2.prototype.hello = function() { // ...
    

    ... assigns a new property to the object referred by object1.

    I don't see how obj and Object2 are connected.

    With var obj = Object.create(object1), you create an object which __proto__ property points to object1. The latter, as we established, is actually the same object Object2.prototype points to.


    I.e setting Object2.prototype to an object without them both referring to the same object?

    If you only want Object2.prototype to copy properties from object1, just clone an object.