【问题标题】:JavaScript delete operator and Object.create() methodJavaScript 删除运算符和 Object.create() 方法
【发布时间】:2020-03-07 07:06:32
【问题描述】:

我正在尝试从 Person 对象中删除一个属性,如下所示:

const Person = {
  firstname: 'John',
  lastname: 'Doe'
}

console.log(Person.firstname);
// Output: "John"

delete Person.firstname;

console.log(Person.firstname);
// Output: undefined

当我使用这个 delete 时,操作符工作正常,Person.firstname 日志显示为 undefined,正如预期的那样。但是,当我使用Person 对象使用Object.create() 方法创建一个新对象时,如下所示:

const Person = {
  firstname: 'John',
  lastname: 'Doe'
}

const Person2 = Object.create(Person);

console.log(Person2.firstname);
// Output: "John"

delete Person2.firstname;

console.log(Person2.firstname);
// expected output: undefined
// actual output: "John"

您可以看到Person2.firstname 最后返回“John”,而我期望它的工作方式与第一个 sn-p 中的相同并返回 undefined

所以,我的问题是:

  • 为什么delete Person2.firstname 不起作用?
  • 另外,我们如何从Person2 对象中删除firstname 属性?

感谢您的帮助。

【问题讨论】:

    标签: javascript object delete-operator object-create


    【解决方案1】:

    delete在要删除的属性是自己的不可配置属性的情况下成功地从对象中删除属性。在这里,您的Person2 确实拥有firstname 自己的属性,因此delete Person2.firstname 不起作用。该属性存在于Person2 的内部原型上,但不存在于Person2 本身上。

    要删除该属性,您必须使用原型对象调用delete

    delete Person.firstname;
    

    const Person = {
      firstname: 'John',
      lastname: 'Doe'
    }
    const Person2 = Object.create(Person);
    delete Person.firstname;
    console.log(Person2);

    或者,如果您还没有对它的引用,请使用Object.getPrototypeOf

    delete Object.getPrototypeOf(Person2).firstname;
    

    const Person = {
      firstname: 'John',
      lastname: 'Doe'
    }
    
    const Person2 = Object.create(Person);
    delete Object.getPrototypeOf(Person2).firstname;
    console.log(Person2);

    【讨论】:

      【解决方案2】:

      你正在创建一个浅拷贝,你想做深拷贝

      这可以通过像

      这样的东西来实现

      const Person = {
        firstname: 'John',
        lastname: 'Doe'
      }
      
      
      
      const Person2 = Object.assign({},Person);
      
      console.log(Person2.firstname);
      // Output: "John"
      
      delete Person2.firstname;
      
      console.log(Person2.firstname);
      // expected output: undefined
      // actual output: "undefined"
      console.log(Person2.lastname)

      this will give you more clarity on shallow and deep copy

      【讨论】:

        猜你喜欢
        • 2016-05-25
        • 2014-08-25
        • 2011-01-02
        • 2012-05-21
        • 1970-01-01
        • 1970-01-01
        • 2016-07-08
        • 2013-01-04
        • 2017-06-08
        相关资源
        最近更新 更多