最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to delete Javascript object property? - Stack Overflow

programmeradmin2浏览0评论

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
  • 3 Both are completely different objects! Not referenced! – Rayon Commented Apr 15, 2016 at 10:23
  • 7 With var newObj = obj; It would work as you are expecting! – Rayon Commented Apr 15, 2016 at 10:23
  • From docs, The Object.create() method creates a "new object" – Rayon Commented Apr 15, 2016 at 10:25
  • 1 Notice that newObj has no name property, so your delete is useless on it. It is newObj's prototype === obj, which has the name property... or not if you deleted it... – GameAlchemist Commented Apr 15, 2016 at 10:35
Add a comment  | 

2 Answers 2

Reset to default 16

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.

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.
发布评论

评论列表(0)

  1. 暂无评论