首页 > 解决方案 > 如何在 JS 中从类中连接函数?

问题描述

我正在尝试解决Edabit上发布的挑战,但我遇到了一个我不太熟悉的语法。这是挑战所需的测试之一:

const ids = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // good so far
const p2 = new Pagination(ids, 5); // good so far
p2.getVisibleItems(); // good so far
p2.nextPage().getVisibleItems(); // what's going on here?

我可以猜测并说这可能是连接函数的一种方式......这是有道理的,但我不知道该怎么做。

这是我到目前为止所取得的成就。

class Pagination {
  constructor(items, pageSize) {
    this.items = items; // Holds the items array
    this.pageSize = pageSize; // Holds the size of each page
    this.totalPages = items.length; // Holds the total number of pages
    this.currentPage = 0; // Holds the current page number
    this.dicPages = {};
  }

  // Methods
  // Goes to the previous page
  prevPage() {
    this.currentPage = this.currentPage - this.pageSize;
    if (this.currentPage < 0) {
      this.currentPage = 0;
    }
    return this.getVisibleItems();
  }

  // Goes to the next page
  nextPage() {
    this.currentPage = this.currentPage + this.pageSize;

    return this.getVisibleItems();
  }

  // Goes to the first page
  firstPage() {
    this.currentPage = 0;
    return this.getVisibleItems();
  }

  // Goes to the last page
  lastPage() {
    var pageIndex = (Object.keys(this.dicPages).length - 1) * this.pageSize;
    this.currentPage = pageIndex;
    return this.getVisibleItems();
  }

  // Goes to a page determined by the `page` argument
  goToPage(page) {
    this.currentPage = page;
    return this.getVisibleItems();
  }

  // Returns the currently visible items as an array
  getVisibleItems() {
    var j = 0;

    for (var i = 0, j = this.items.length; i < j; i += this.pageSize) {
      this.dicPages[i] = this.items.slice(i, i + this.pageSize);
    }

    return this.dicPages[this.currentPage];
  }
}

const ids = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const p2 = new Pagination(ids, 5);

console.log(p2.getVisibleItems()); //,            [0, 1, 2, 3, 4]
console.log(p2.nextPage().getVisibleItems()); //, [5, 6, 7, 8, 9]
console.log(p2.nextPage().getVisibleItems()); //, [10]

标签: javascriptoop

解决方案


推荐阅读