在js类中作为参数传递的函数setTimeout立即执行,并在setTimeout中调用类方法

时间:2017-02-24 00:49:37

标签: javascript

Js类方法getInfo应在5秒延迟后调用alert,但它会立即触发

function limiter (limit,hid,sid) {
    this.limit = limit;
    this.hid = hid;
    this.sid = sid;


    this.getInfo = function(aca) {

       setTimeout(alert(aca), 5000);
    };
}


var limiter= new limiter(5,5,5);

limiter.getInfo("loko roko");

1 个答案:

答案 0 :(得分:3)

alert事件放在函数中。



function limiter(limit, hid, sid) {
  this.limit = limit;
  this.hid = hid;
  this.sid = sid;
  console.log(this.limit);

  this.getInfo = function(aca) {
    setTimeout(() => {
      console.log(this.limit);
      alert(aca)
    }, 5000);
  };
}

var limiter = new limiter(5, 5, 5);

limiter.getInfo("loko roko");