Reputation: 765
I am trying to delete a object property which is shallow copy of another object. But the problem arises when I try to delete it, it never goes off while original value throws expected output.
var obj = {
name:"Tom"
};
var newObj = Object.create(obj);
delete newObj.name;//It never works!
console.log(newObj.name);//name is still there
Upvotes: 13
Views: 11279
Reputation: 382102
newObj
inherits from obj
.
You can delete the property by accessing the parent object:
delete Object.getPrototypeOf(newObj).name;
(which changes the parent object)
You can also shadow it, by setting the value to undefined
(for example):
newObj.name = undefined;
But you can't remove the property on newObj without deleting it from the parent object as the prototype is looked up the prototype chain until it is found.
Upvotes: 16
Reputation: 67197
Basically Object.create
will create an object , set its prototype as per the passed object and it will return it. So if you want to delete
any property from the returned object of Object.create
, you have to access its prototype.
var obj = { name:"Tom" };
var newObj = Object.create(obj);
delete Object.getPrototypeOf(newObj).name
console.log(newObj.name); //undefined.
Upvotes: 4