从with函数访问类方法

时间:2018-07-25 09:08:54

标签: javascript

我只是试图从另一个类方法中的函数中访问一个类方法,所以:

class test
{
 show()
 {
  setTimeout(function()
  {
    this.showInside()
  },0)

 }

 showInside()
 {
    alert("WORKING")
 }



}

var test2 = new test();
test2.show()

我显然做错了,很明显我不能在该函数中使用this.showInside(),但我不知道该怎么做...

有帮助吗?

1 个答案:

答案 0 :(得分:0)

this取决于上下文。在setTimeout内部,this没有引用实例。这是一个工作示例:

class test
{
  constructor(){};

 show(){
  setTimeout((function(){ this.showInside() }).bind(this),0)
 }

 showInside(){
    alert("WORKING");
 }

}

var test2 = new test();
test2.show();