代码之家  ›  专栏  ›  技术社区  ›  Todd Davis

如何在JavaScript中正确初始化子函数?

  •  0
  • Todd Davis  · 技术社区  · 5 年前

    请考虑以下代码。此代码按预期工作。

    function paging(totalItems, currentPage, itemsPerPage) {
      this.totalItems = (typeof totalItems !== 'undefined') ? totalItems : 0;
      this.currentPage = (typeof currentPage !== 'undefined') ? currentPage : 1;
      this.itemsPerPage = (typeof itemsPerPage !== 'undefined') ? itemsPerPage : 18;
    }
    
    function viewModel(foo, bar, paging) {
      this.foo = (typeof foo !== 'undefined') ? foo : true;
      this.bar = (typeof bar !== 'undefined') ? bar : false;
      this.paging = (typeof paging !== 'undefined') ? paging : {};
    }
    
    function init() {
      // Create a new viewmodel object and assign it to $scope (AngularJS)
      $scope.viewModel = new viewModel();
      // Set the paging parameter to a new paging object
      $scope.viewModel.paging = new paging();
      // Now we can use dot notation to assign the value in the sub-function
      $scope.viewModel.paging.currentPage = 1;
    }
    
    init();
    

    现在,我正在尝试做的,但还不太清楚,是如何调用“new viewModel()”,并让分页属性自动填充一个新的分页(),而不必在init()中进行额外的调用。例如,这样的事情。。。

    function viewModel(foo, bar, paging) {
      this.foo = (typeof foo !== 'undefined') ? foo : true;
      this.bar = (typeof bar !== 'undefined') ? bar : false;
      this.paging = (typeof paging !== 'undefined') ? paging : new paging();
    }
    

    如果我没记错的话,这会抛出一个关于构造函数的错误。

    我也试过这个:

    function viewModel(foo, bar, paging) {
      this.foo = (typeof foo !== 'undefined') ? foo : true;
      this.bar = (typeof bar !== 'undefined') ? bar : false;
        function paging(totalItems, currentPage, itemsPerPage) {
          this.totalItems = (typeof totalItems !== 'undefined') ? totalItems : 0;
          this.currentPage = (typeof currentPage !== 'undefined') ? currentPage : 1;
          this.itemsPerPage = (typeof itemsPerPage !== 'undefined') ? itemsPerPage : 18;
        }
    }
    

    …以及上述的几种其他形式,但除了原始示例外,似乎没有什么能正确初始化分页属性。难道没有更好的方法来处理这个问题吗?

    0 回复  |  直到 5 年前
    推荐文章