为什么这个属性不想被删除

时间:2014-10-11 11:07:56

标签: javascript

仅出于实验目的而编写此代码。在这里,我使用Object.defineProperty创建一个名为'fullName'的属性,并使用set i将另一个属性定义为名为middleName的人。我必须通过middleName将值传递给fullName。它们都有可枚举的属性TRUE,因此for..in循环可以访问它。但是我想删除middleName来自对象的属性。但它仍然存在。为什么它仍然存在?



(function(){
  person = {
    firstName: 'will',
    lastName: 'Smith'
  };

  Object.defineProperty(person,'fullName',{

    set:function(mid){
      Object.defineProperty(person,'middleName',{
        value     : mid,
        enumerable: true,
        writeable : false
      });
    },
    get:function(){
      document.write(this.middleName);
    },
    enumerable:true
  });

  person.fullName='lol';
  person.fullName;	
  document.write(Object.getOwnPropertyNames(person)+'</br>');	

  for(key in person){
    document.write(key+'</br>');
  }		

  document.write('\n');		 
  delete (person.middleName);
  document.write(person.middleName+'</br>');

  for(key in person){
    document.write(key+'</br>');
  }
})()
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

使用Object.defineProperty时,默认情况下可配置属性设置为false(请参阅ToPropertyDescriptor,步骤4),因此 middleName 属性不可删除。

请注意:

delete (person.middleName);

括号是多余的,应写成:

delete person.middleName;

一个简单的例子是:

// Create object o
var o = {};

// Define property a with value bar
Object.defineProperty(o, 'a', {
  value : 'bar'
});

console.log(o.a); // bar

// Since the configurable property of a was not set, it defaults to false
// so it can't be deleted
delete o.a;

console.log(o.a); // bar

// Create property b with value fum and configurable true
Object.defineProperty(o, 'b', {
  value : 'fum',
  configurable: true
});

console.log(o.b); // fum

// Since b's configurable attribute is true, it can be deleted
delete o.b;

console.log(o.hasOwnProperty('b')); // false
console.log(o.b); // undefined