Search code examples
javascriptobjectpropertiesassign

Javascript Assign and delete properties


Can someone explain me what exactly is happening here?

var myObject = {
  price: 20.99,
  get_price: function() {
    return this.price;
  }
};

var customObject = Object.create(myObject);
customObject.price = 19.99;
delete customObject.price;
console.log(customObject.get_price()); //returns 20.99


Solution

  • This happened due to the consequences of prototype-chain. The statement

    var customObject = Object.create(myObject);
    

    creates an object with its prototype set as myObject. Now you're assigning and deleting the property price on it. But it doesn't change what's already there in its prototype.

    You can try that by printing customObject to the console prior to deleting the property price. You will see that the object contains a property price with value set as 19.99, but its __proto__ property's price is still 20.99. Run the following snippet, and observe the output in your browser's console.

    var myObject = {
      price: 20.99,
      get_price: function() {
        return this.price;
      }
    };
    
    var customObject = Object.create(myObject);
    customObject.price = 19.99;
    console.log(customObject);

    The function get_price returns this.price, which searches for a property price in the current object, and if not found, it recursively traverses the prototype-chain for this property. Since this property existed in the immediate prototype of the object, the value 20.99 is returned.