2014-10-11 29 views
0

寫到這代碼只用於試驗目的。在這裏,我用Object.defineProperty創建一個名爲'fullName'性質和使用set我定義的另一個屬性叫middleName人。我不得不通過fullName。無論他們有枚舉財產TRUE傳遞價值middleName,使for..in迴路可以訪問它。但是後來我想從刪除中間名屬性object.But它仍然是there.Why它仍然存在??爲什麼這個屬性不希望被deleated

(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; \t 
 
    document.write(Object.getOwnPropertyNames(person)+'</br>'); \t 
 

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

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

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

+0

'delete'操作者意圖與**變量**一起使用。 'person.middleName +「
」'你試圖刪除是** **表達式是 – hindmost 2014-10-11 11:13:38

+0

是當我在編輯文章。它不包括在實際code.I打錯了已編輯post.check它,請 – 2014-10-11 11:15:35

+0

@天誅地滅,我想你指的是[*刪除*運算符(http://ecma-international.org/ecma-262/5.1/#sec-11.4.1)可以刪除對象的屬性,不變量(參見[ MDN(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete))。 – RobG 2014-10-11 11:25:19

回答

2

當使用Object.defineProperty,所述可配置屬性被默認設置爲false(見ToPropertyDescriptor,步驟4),以使中間名屬性不刪除的。

注意,在:

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 
+0

很好的解釋..感謝:) – 2014-10-11 18:54:56

相關問題