简体   繁体   中英

Can not use the `this` in my callback function

I have a Util method:

util.delete_selection = function (context, delete_url_func, selection, cb=undefined) { ... }

and when I use the delete_selection method, I pass the cb like bellow, there will get a issue, I can not in the callback function to use the this :

Util.delete_selection(
      this,
      this.delete_url_function,
      this.selection,
      function (bool) {
        debugger
        this.$emit('callback')   // there the `this` is undefined.
        console.log('cb')
      }
    )

And I tried use the arrow function to replace it, find it can not use the arrow function there.


EDIT

When I use the arrow function like bellow, the WebStorm will report error there:

在此处输入图片说明

If I change the bool to other param name, it still get error:

在此处输入图片说明

you might want to replace
function (bool) {
with
bool => {

but since you don't even use bool itself, you could omit it and write: () => { instead.

why?

that's a lambda. it does not have it's own context.
function however has.
this inside function blocks always refer to the function scope and not the scope of the upper layer.

you can always override the context of a function using either .bind(context) to cause a rebind or use .call(context, ...arguments) or .apply(context, [...arguments]) but a lambda would probably be a good idea here.


using a lambda should actually work here. just run this and you see it in action:

 const data = [{ some: 'thing', text: 'foo' }, { some: 'thing else', text: 'bar' }]; const doSomething = function (arg, func) { console.log('some:', arg.some); func(); }; data.map(context => { (function () { doSomething(this, () => { console.log('text:', this.text); }); }).call(context); }); 

Since, this gives the reference of the container inside which it is being used, when you use this inside callback it gives you the scope of the callback function and not the parent function. Thus, you can bind this in the callback as:

Util.delete_selection(
      this,
      this.delete_url_function,
      this.selection,
      function (bool) {
        this.$emit('callback')
        console.log('cb')
      }.bind(this)
    )

this in javascript is a bit confusing. Have a look: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

You need to bind this to the callback

Util.delete_selection(
      this,
      this.delete_url_function,
      this.selection,
      function (bool) {
        debugger
        this.$emit('callback')   // there the `this` is undefined.
        console.log('cb')
      }.bind(this)
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM