Search code examples
javascripthtmlobjectprototypal-inheritance

Why Obj2 does not find function by prototype from Obj1 via Object.Create()


I am trying to look at inheritance via Object.create(). I have created Obj1 and added some properties & Methods in it. Now when I am doing obj2 = object.create(obj1);, so all properties and methods must also be coming to it via prototype inheritance. Finally, why on finding obj2.findAge() is not giving result? Please, can someone help and rectify it?

<html> 
<head></head> 
<body> 
<script> 
var obj1 = {
    name: "Peter Martin",
    age: 29,
    printName: function(){
        console.log(this.name);
    },
    printAge: function(){
        console.log(this.age);
    }
}
var obj2 = Object.create(obj1);
obj2 = {
    name: "Ronald Jane",
    printName: function(){
        console.log("Hello Dear" + this.name);
    }
}
obj1.printName();
obj1.printAge();
obj2.printName();
obj2.printAge();
</script> 
</body> 
</html> 

What I want to do is use Object.Create() to get inhertiance from Obj1 to Obj2 with Obj2 having some of its own private properties. Please, help me out get this done in this example.


Solution

  • After Object.create you have assigned the new object reference into the obj2, but after it you have changed the reference again when you did obj2 = { ... }, so you lost the last one. If you want to add additional properties into the object, you can use overridden version of Object.create or just add it via . and [] syntax.

    What about findAge (You mentioned in the post) I don't see it anywhere

    var obj1 = {
        name: "Peter Martin",
        age: 29,
        printName: function(){
            console.log(this.name);
        },
        printAge: function(){
            console.log(this.age);
        }
    }
    var obj2 = Object.create(obj1, { 
       name: { value: 'Ronald Jane', writable: true},
       printName: { value: function() {
            console.log("Hello Dear " + this.name);
       }}
    });
    //obj2 = { // Here you change `obj2` to refer another object, so you have lost anything which is related to `Object.create(obj1)`
    //    name: "Ronald Jane",
    //   printName: function(){
    //        console.log("Hello Dear" + this.name);
    //    }
    //}
    obj1.printName();
    obj1.printAge();
    obj2.printName();
    obj2.printAge();