typescript to javascript call back function can no

2019-08-17 15:27发布

问题:

I can not access typescript global variable from javascript call of callback function passed of same typescript method.

Here is an example code in stackblitz.

https://stackblitz.com/edit/angular-quhktp

In example above incr variable which is declared in component file. Can be accessed in clickthisfunction method when we directly use it. But if the same method passed to javascript for a call back. call back function is called but this method couldn't access this.incr variable.

回答1:

In functions in javascript, this refers to the object on which the function was called. So if you call this.clickthisfunction(), this.incr works fine, but if you reassign this.clickthisfunction to some other variable, the this in that function won't be what you expect. This MDN page has more information about how this works.

To fix this, there are a few options:


bind:

You can change what the this value in a function will be by calling .bind on it. You can do this in the constructor by adding this line:

this.clickthisfunction = this.clickthisfunction.bind(this);

You can also bind it right before you pass it to withargumentcallwithfunctionasargument, but binding isn't free, so it's more typical to only do it once.


Arrow functions:

Arrow functions handle this differently – they capture it from the outer scope instead of using the object the function was called on.

By replacing the function declaration with this

clickthisfunction = () => {

it will capture the this value from when the object is constructed. (If you are interested how it's getting the this value, look at the transpiled code, it makes a lot more sense).


Either one of these should fix this being undefined, and which you use is mostly a matter of style. The only difference is that the first approach will leave a function on the prototype, while the second will only have the function on the instances. That probably won't affect anything, though, unless you do something strange.



回答2:

One little mistake there. You need to call it when you pass it.

This should do the trick:

  clickthisargwithfunction() {
    withargumentcallwithfunctionasargument(this.clickthisfunction());
  }