繁体   English   中英

从另一个类属性 (ES6) 计算出的类属性

[英]Calculated Class property from another Class Property (ES6)

我有一个带有构造函数的类,如下所示:

class Bookshelf {  
 constructor(author, publisher) {
  this.books = [],
  this.numBooks = this.books.length
  this.author = author,
  this.publsiher = publisher
 }
}

我没有取回我真正想做的 book 数组的值。 我知道this会导致价值不被抓取,但我真的很想知道为什么?

我根据标题将这个问题解释为询问为什么numBooks在您创建的Bookshelf内的books添加条目后不更新。

当您运行语句this.numBooks = this.books.length ,它确实将一个名为numBooks的属性设置为计算值this.books.length ,即0 稍后,您可能会向books添加一个值,但这不会影响numBooks

问题不在于从另一个计算一个“类属性” ,而在于理解numBooks存储一个数字,并且该数字不会自动更新 你的构造函数运行一次,就是这样。

与此比较:

class Bookshelf {  
 constructor(author, publisher) {
  this.books = [];
  this.author = author;
  this.publisher = publisher;
 }

 getNumBooks() {
  return this.books.length;
 }
}

let myBookshelf = new Bookshelf("Isaac Asimov", "Bantam Press");
myBookshelf.books.push("I, Robot");
console.log(myBookshelf.getNumBooks());   // prints 1

因为您对getNumBooks()调用运行代码,所以它可以计算动态值this.books.length ,这就是它为您提供最新值的原因,其中属性numBooks不会自动更新。 如果您希望将numBooks作为属性保留,您还可以选择将books属性addBook私有,而是公开一个addBook函数,该函数添加一本书并相应地重置numBooks

正如 Patrick 在评论中提醒我的那样,由于您指定了 ES6,您可以使用getter 语法来编写一个充当属性的函数。 这是有效的,因为它在您引用numBooks时运行代码,即使语法隐藏了该细节。

class Bookshelf {  
 constructor(author, publisher) {
  this.books = [];
  this.author = author;
  this.publisher = publisher;
 }

 get numBooks() {
  return this.books.length;
 }
}

let myBookshelf = new Bookshelf("Isaac Asimov", "Bantam Press");
myBookshelf.books.push("I, Robot");
console.log(myBookshelf.numBooks());   // prints 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM