1

I am having trouble understanding delete operation in javascript.

I have an object like follows -

var object = {"name" : "abc"};

object.prototype = {"name" : "xyz"};

If I delete the "name" property from object it should delete it from the object and not from the prototype as the prototype values are only used in get operation.

So after -

delete object.name

If I print object.name it gives me 'undefined', while in my opinion it should give me 'xyz'.

First i thought that the delete operation is just setting the value of object.name to 'undefined', but then object.hasOwnProperty('name') gives me false.

Am I missing anything?

2
  • 1
    If I print object.name it gives me 'undefined', while in my opinion it should give me 'xyz'. It seems that you confuse object.name and object.prototype.name Commented Mar 23, 2016 at 10:36
  • The behavior you describe would occur only if the prototype occurs in the prototype chain. Commented Mar 23, 2016 at 10:40

1 Answer 1

7

The hole in your understanding is with prototypes, not delete.

Values on the prototype appear on instances of an object, not the object to which the prototype property belongs.

You need to create a constructor function, put the prototype on that, then instantiate an object from that function using new.

function MyObject (name) {
  this.name = name;
}

MyObject.prototype.name = "xyz";

var instance = new MyObject("abc");

document.write(instance.name);
document.write("<br>");
delete instance.name;
document.write(instance.name);

Sign up to request clarification or add additional context in comments.

2 Comments

Great answer but I'm struggling with "Values on the prototype appear on instances of an object, not the object to which the prototype property belongs" - can anyone expand a little, please?
@WillJenkins — Umm. I did. In the next paragraph.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.