如何在另一个对象中使用一个对象的属性

时间:2016-03-01 15:41:19

标签: javascript inheritance

我想创建自己的类,让我们说Data,其中包含File以及有关它的其他信息:

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

但我想直接从我的对象Data中读取有关文件的信息,例如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到Data的继承属性? 当然,File必须仍然可以访问(例如,使用它来发送xhr.send()

2 个答案:

答案 0 :(得分:2)

  

所以现在Data.size可以访问

我将假设您的意思是,如果您执行var d = new Data(...);,则可以访问d.size

如果是这样,您可以通过Object.definePropertyMDN | spec)定义属性访问者来执行此操作(在ES5及更高版本中):



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>
&#13;
&#13;
&#13;

像IE8中那样的过时的JavaScript引擎无法处理它,但所有现代的引擎都会。

答案 1 :(得分:0)

可能是getter属性的一个很好的用例:

Object.defineProperty(Data.prototype, 'size', {
   get: function () {
       return this.file.size;
   }
});

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty