2015-04-12 53 views
5

ECMAScript版本5規範引入了一種稱爲訪問器屬性的新屬性。與名爲數據屬性的現有和已知類型的屬性相比,這兩件事情在規範方面是如何相互關聯的?ECMAScript中訪問器屬性和數據屬性之間的區別?

我已經閱讀了ECMAScript v5的規格說明,並且我不清楚確切的區別。有人可以用代碼示例解釋兩者嗎?我搜索了互聯網,但所有的例子都很模糊。

+2

在問別人重複規範說什麼之前,你甚至還試過了解它嗎? – Touffy

+0

@Touffy是的,我讀了ecmascript規範,但我仍然不明白accessor屬性如何保存數據,而不具有value屬性以及data屬性和accessor屬性之間的差異。 – ringord

+0

查看https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Description –

回答

8

命名數據屬性將名稱與值關聯。這意味着您可以使用該屬性直接獲取和檢索數據,如類上的公共字段。

已命名的訪問器屬性將名稱與一個或兩個訪問器函數關聯。 訪問器函數用於存儲或檢索與屬性關聯的值。這意味着您將訪問權限限制在get或/和set訪問器屬性後面的某個值。

通過比較兩者,第一個選項不會對您的值的訪問方式進行封裝或控制。第二個讓你指定你的值可以被讀取'get accessor','set accessor'或兩者。

UPDATE

關於您的第二個疑問(在評論)這裏是我剛剛熟ECMA腳本基礎一點點,快101):

// accounting namespace 
var Accounting = {}; 

// client class definition 
Accounting.Client = function(){ 
    // private fields 
    var _address=""; 
    var _phone=0; 

    // data property 
    this.token = ""; 

    // privileged properties 
    Object.defineProperty(this, "address", { 
     get: function(){ 
      if(console) console.log('hey im using get address accessor property.');   
      return _address; 
     }, 
     set: function(value){ 
      if(console) console.log('hey im using set address accessor property.'); 

      if(value == null) 
       throw new Error('Field address cannot be null!'); 

      _address=value; 
     } 
    }); 

    Object.defineProperty(this, "phone", { 
     get: function(){ 
      if(console) console.log('hey im using get phone accessor property.'); 
      return _phone; 
     }, 
     set: function(value){ 
      if(console) console.log('hey im using set phone accessor property.'); 
      _phone=value; 
     } 
    }); 
}; 

Accounting.Client.prototype = { 
    sayHello: function(){ 
     alert("hello im a shared function, which means im shared by all objects of type Client" 
       + " and i do not have access to private fields :(."); 
    } 
}; 


/* use case */ 
var c1 = new Accounting.Client(); 
c1.address = "Rua da Capela"; 
c1.phone = 961909090; 
c1["token"] = "mytoken in a data property"; 
c1.token = c1.token + "-111"; 

alert("client address is '" + c1.address + "' and his phone also is '" + c1.phone + "'."); 
c1.sayHello();  
alert(c1.token); 

try{ 
    // check non nullable field. 
    c1.address=null; 
} 
catch(ex){ 
    alert(ex); 
} 

使用我jsfiddle玩耍!

快樂編碼!

相關問題