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
2 Answers 2
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.
3 Comments
_proto_ is not recommended. Isn't it?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.
5 Comments
delete obj.name; line, too. Without that one, name is still here in newObj (sort of), indeed.
referenced!var newObj = obj;It would work as you are expecting!newObjhas nonameproperty, so your delete is useless on it. It isnewObj's prototype ===obj, which has thenameproperty... or not if you deleted it...