在Object Javascript中的另一个方法中调用方法时出错

时间:2017-12-18 19:37:27

标签: javascript javascript-objects

我的代码有点问题,我有一个对象,我有一个错误 Paginator.validate不是函数 ,我调用方法validate()从Object的相同范围内的另一个方法,下面的代码,我真的很感谢你的帮助:D,欢呼!

function Paginator(res){
    this.total = res['data']['TotalRegistros'];
    this.resPorPagina = res['data']['RegistrosPorPagina'];
    this.pagActual = res['data']['PaginaActual'];
    this.registros = res['data']['Registros'];

    this.paginas = function(){
        return Math.round(this.total/this.resPorPagina);
    }

    this.render = function() {
        var table;
        $.each(this.registros,function(index,element){
            table += '<tr>';
            $.each(element,function(i,e){
                table += '<td>' + Paginator.validate(e) + '</td>';
            })
            table += '</tr>';
        });
        return table;
    }

    this.validate = function(e){
        if(e == null || e == false){e = 'Sin Info';}
        return e;
    }

    this.paginator = function(){
        var b = '';
        for (var i=1;i<=Paginator.paginas();i++) {
            active =  (this.pagActual === i)?'active':'';
            b += '<li class="'+active+'"><a class="btn_paginate" href="#" data-page="'+i+'">'+i+'</a></li>';
        }
        return b;
    }
}
var res = //i get the data from a ajax call in PHP
// object Paginate
var Paginate = new Paginator(res);
// object Paginate
$('#reportsTable tbody').append(Paginate.render());
$('.paginate').find('ul').html(Paginate.paginator());

1 个答案:

答案 0 :(得分:3)

问题是jquery函数中Paginator的上下文不是this。您需要在某处创建对this.render = function() { var table; var self = this; $.each(this.registros,function(index,element){ table += '<tr>'; $.each(element,function(i,e){ table += '<td>' + self.validate(e) + '</td>'; }) table += '</tr>'; }); return table; } 的引用。尝试:

const routes: Routes = [
  {path: '', component: ListPageComponent},
  {path: 'd/:id', component: DetailsPageComponent},
  {path: ':param1', component: ListPageComponent},
  {path: ':param1/:param2', component: ListPageComponent},
  {path: ':param1/:param2/:param3', component: ListPageComponent},
  {path: '**', component: ListPageComponent}
];