javascriptecmascript-3

Deleting properties in two ways, but only one works


delete removes property from some object.

function Man() {
  this.eye = 2;
  this.mouth = 1;
}
Man.prototype.walk = function (arguments) {
  console.log("Im walking.");
}

var man1 = new Man();
var man2 = new Man();

delete man1.constructor;
console.log(man1.constructor); // function Man()

Up there, by delegation of course, I am deleting the property of man1's prototype, the constructor property. Well, at least that is my intention. But when I log, I still get the Constructor function.

However, this problem is fixed when

delete man1.constructor.prototype.constructor;
console.log(man1.constructor);  // function Object()

now what I get is empty Object. As I should.

My question is: why does that second solution work and the first one does not? Is it because of delegation? I have heard that the one that works delete man1.constructor.prototype.constructor; uses "implicit" reference. What does that mean? One more thing. Why am I still getting empty Object and no free memory?


Solution

  • Why you get the constructor again ?

    Because delete works only for the direct/own properties of the object, but your Man does not have a direct/own property with name constructor. constructor is in the prototype chain of the Man which comes from the Man.prototype. When you access that property it just goes and gets it from the prototype chain.

    So from here you can also infer that properties from the prototype chain can only be read, not modified. If you want to modify, you need a direct access.

    However, this problem is fixed when

    In this case you have accessed actually the original object and delete it from that object. For that object constructor is a direct/own property.