2016-07-24 78 views
0

我试图访问我的MyAccount类中的私有方法,但它给出的错误为uncaught typeError: this.displayTabOnClick not a function。我可以清楚地确认这是一种私人方法,在MyAccount课程中可用,其他类似方法displayTabOnPageLoad完美。未捕获的类型错误:不是TypeScript中私有方法的函数

下面的代码片段:

MyAccount.ts文件

class MyAccount 
{ 
    private displayTabOnClick(thisObj: JQuery, e:Event, callback?:()=>any): void { 
    $(document).scrollTop(0); 
    e.preventDefault() 
    let hash = thisObj.prop('hash'); 

    // Update the location hash 
    window.location.hash = hash; 

    // Add Selected class to the current click elem 
    // Remove selected class from other .menu-link elem 
    thisObj.addClass('selected'); 
    $('.menu-link').not(thisObj).removeClass('selected'); 

    // Set Tab Header 
    this.setHeader(hash); 

    // Hide all sections 
    // And display only the hashed section 
    $('section').css('display','none'); 
    $(hash).css('display','block'); 
    } 

    /** 
    * Switch My Account Tab 
    * According to the passed ID 
    * 
    * @return void 
    */ 
    public switchTab (e?: Event): void { 
     if (e && e.type === "click") { 
      this.displayTabOnClick($('.menu-link'),e); 
     } 
     else { 
      this.displayTabOnPageLoad($('.menu-link')); 
     } 
    } 
} 

App.ts文件

// My Account Page 
let page = new MyAccount; 

if (URL.checkPath('/user/myaccount')) { 
    page.switchTab(); 
} 

$('.menu-link').click(page.switchTab); 
+0

试图编译此代码。如果排除缺少的方法,则不会出现错误。这两种方法有什么区别?实施似乎并不重要。尝试定义一个最简单的例子。 –

+0

page.switchTab()正在执行,但它传递给点击处理程序时它相同的功能typeerror – ChanX

回答

1

你有调用$('.menu-link').click(page.switchTab);时范围界定问题(的作用范围是主叫方,而不是到page

其中一个选项来解决它:

$('.menu-link').click(e => page.switchTab(e)); 

还有一句:

$('.menu-link').click(page.switchTab.bind(page)); 

因为它保持了类型安全,所以我会选择第一个。

+0

是啊..我怎么能忘记'this'的词法范围..我的错误..让我试试你的代码 – ChanX

+0

顺便说一句我不想传递'事件'作为参数,因为我可以得到该对象,而不通过参数 – ChanX

+0

仍然无法正常工作 – ChanX

相关问题