Search code examples
javascriptprototype

Can an object have properties which its prototype doesn't have?


In JavaScript, must an object and its prototype (i.e. its property prototype as an object) have exactly the same set of properties?

Can an object have properties which its prototype doesn't have?


Solution

  • In JavaScript, must an object and its prototype (i.e. its property prototype as an object) have exactly the same set of properties?

    No. The prototype is used to create instances of objects. At the moment an instance is created, the instance becomes a separate object from the prototype and modifications to it don't affect the prototype (however, changes to the prototype will affect the instance). Welcome to prototypical inheritance!

    Can an object have properties which its prototype doesn't have?

    Yes, here's an example:

    function foo(){
      // doesn't matter what it does
    }
    
    let fooInstance = new foo();
    
    console.log(foo.prototype.bar); // undefined
    console.log(fooInstance.bar);   // undefined
    console.log("************************");
    
    // Give the instance object a new property.
    // This does not create a property on the instance's prototype
    fooInstance.bar = "baz";
    
    console.log(foo.prototype.bar); // undefined
    console.log(fooInstance.bar);   // baz
    console.log("************************");
    
    console.log(foo.prototype.hasOwnProperty("bar"));  // false
    console.log(fooInstance.hasOwnProperty("bar"));    // true