'this' is undefined inside function(). ang

2020-02-13 02:09发布

问题:

So I am using a uikit confirmation modal in my app. My problem is, when I am going to click the <button> for confirmation. the this inside function is undefined. here's my code...

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!');  
    });
}

Inside that function I wish to use service for http request but I am having a problem on the this. I am using Angular 2.x.

回答1:

Use an arrow function...

declare var UIkit:any;

deleteData(dataArr): void {

  UIkit.modal.confirm('Are you sure you want to delete this?', () => {

    console.log(this);
    // [...]
  });
}

Check out MDN: Arrow functions for details on the matter.

An arrow function does not create its own this context, so this has its original meaning from the enclosing context.



回答2:

'this' is not passed to your function scope, try

declare var UIkit:any;

deleteData(dataArr): void {
var that = this;
UIkit.modal.confirm('Are you sure you want to delete this?', function(){
  console.log(dataArr);
  console.log(that);
  //use service here...
  UIkit.modal.alert('Confirmed!');  
});
}