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
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
Share
Improve this question
edited Apr 15, 2016 at 12:27
manuell
7,6205 gold badges33 silver badges62 bronze badges
asked Apr 15, 2016 at 10:22
fruitjsfruitjs
7652 gold badges11 silver badges25 bronze badges
4
|
2 Answers
Reset to default 16newObj
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.
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.
referenced
! – Rayon Commented Apr 15, 2016 at 10:23var newObj = obj;
It would work as you are expecting! – Rayon Commented Apr 15, 2016 at 10:23newObj
has noname
property, so your delete is useless on it. It isnewObj
's prototype ===obj
, which has thename
property... or not if you deleted it... – GameAlchemist Commented Apr 15, 2016 at 10:35