相关疑难解决方法(0)

JavaScript中的setTimeout和"this"

我有一个使用该setTimeout函数的方法,并调用另一个方法.在初始加载方法2工作正常.但是,在超时后,我收到一个错误,表示method2未定义.我在这做错了什么?

例如:

test.prototype.method = function()
{
    //method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";
    timeDelay = window.setTimeout(this.method, 5000);
};

test.prototype.method2 = function(name) {
    for (var i = 0; i < document.images.length; i++) {
        if (document.images[i].id.indexOf(name) > 1) {
            return document.images[i];
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

javascript

32
推荐指数
4
解决办法
3万
查看次数

使用类/异步等待时获得未定义的“this”

我刚刚开始尝试类和异步等待。我使用的是 Node 版本 8.9.0 (LTS)。当 I 时console.log(this),我得到undefined而不是对对象的引用。

子处理程序.js

class Handler {
  constructor(props) {
    this.defaultRes = {
      data: successMessage,
      statusCode: 200
    };
  }

  async respond(handler, reply, response = this.defaultRes) {
    console.log(this); // why is `this` undefined????
    try {
      await handler;
      return reply(response.data).code(response.statusCode)
    } catch(error) {
      return reply(error);
    }
  }
}

class SubHandler extends Handler {
  constructor(props) {
    super(props);
    this.something = 'else';
  }

  makeRequest(request, reply) {
    console.log(this); // why is `this` undefined!!
    // in this case, doSomeAsyncRequest is …
Run Code Online (Sandbox Code Playgroud)

javascript async-await ecmascript-6 hapijs ecmascript-2017

7
推荐指数
1
解决办法
4112
查看次数

'this'在function()中未定义.角2

所以我在我的应用程序中使用了uikit确认模式.我的问题是,当我要点击<button>确认时.在this内部功能undefined.这是我的代码......

declare var UIkit:any;

deleteData(dataArr): void {

    UIkit.modal.confirm('Are you sure you want to delete this?', function() {
      console.log(dataArr);
      console.log(this);
      //use service here...
      UIkit.modal.alert('Confirmed!');  
    });
}
Run Code Online (Sandbox Code Playgroud)

在该函数内部我希望使用http请求服务,但我遇到了问题this.我正在使用Angular 2.x.

javascript typescript ecmascript-6 angular

3
推荐指数
1
解决办法
6075
查看次数