2016-03-01 48 views
0

我要創造我自己的類使用一個對象的屬性,可以說Data其中將包含File和有關它的信息:如何在另一個

Data = function(file, oneInfo, anotherInfo, moreInfo) { 
    this.file = file; 
    this.property1 = oneInfo; 
    this.property1 = anotherInfo; 
    this.property1 = moreInfo; 
}; 

但我想直接閱讀文件的信息從我的對象數據,例如Data.size 我能做到這一點(醜陋的)是這樣的:

Data = function(file, oneInfo, anotherInfo, moreInfo) { 
    this.file = file; 
    this.size = file.size; 
    this.property1 = oneInfo; 
    this.property1 = anotherInfo; 
    this.property1 = moreInfo; 
}; 

所以現在Data.size是可訪問的,但在那裏,我可以使用,而不調用文件屬性的任何其它方式Data.file.size或我的醜陋版本? 也許某種從文件到數據的繼承屬性? 當然File必須是仍然可以訪問(例如使用它通過xhr.send()發送)

+1

*「現在可以訪問Data.size」*不,它不是。 「數據」仍然沒有「大小」。然而,通過'new Date'創建的對象的確是你的意思? –

+0

什麼是醜陋的?僅僅是你必須爲每個屬性手動執行此操作(以至於它變得單調乏味),還是有可能文件將在背後改變,並且希望保持屬性同步? – TheHansinator

+0

是的,新的數據對象將具有該屬性 – lol2x

回答

2

所以現在Data.size是可訪問的

我會假設你的意思是,如果你這樣做var d = new Data(...);,然後d.size訪問。

如果是這樣,你可以通過Object.defineProperty定義屬性訪問做到這一點(在ES5及更高版本)(MDN | spec):

function Data(file) { 
 
    this.file = file; 
 
} 
 
Object.defineProperty(Data.prototype, "size", { 
 
    // The "getter" is called when you _get_ the value 
 
    // You don't have to define one, though it's odd if you don't 
 
    get: function() { 
 
    return this.file && this.file.size; 
 
    }, 
 
    // The "setter" is called when you _set_ the value 
 
    // You don't have to define one; if you don't the property is read-only 
 
    set: function(value) { 
 
    if (this.file) { 
 
     this.file.size = value; 
 
    } 
 
    } 
 
}); 
 

 
// Initial setup 
 
var f = { 
 
    size: 10 
 
}; 
 
var d = new Data(f); 
 
snippet.log(d.size); // 10 
 

 
// Changing f.size affects what you get back from d.size 
 
f.size = 20; 
 
snippet.log(d.size); // 20 
 

 
// Changing d.size changes f.size 
 
d.size = 30; 
 
snippet.log(f.size); // 30
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

過時的JavaScript引擎像IE8中的一個將無法處理它,但所有現代的都可以。

+0

謝謝,和很棒的snippet.js,肯定會使用:D – lol2x