Home > other >  how to change `this` pointer in typescript
how to change `this` pointer in typescript

Time:09-21

I want to create a Image data and rewrite onl oad function , but this can't point to newImage in typescript. what can i do to make this pointer point to newImage

enter image description here

CodePudding user response:

According to the code you provided I do not see a way to use this pointer as newImg. But you will be able to use const{width,height} = newImg.somethingYouWannaDo().

CodePudding user response:

You can tell TypeScript which type this should have by adding it as a function parameter:

function onload(this: HTMLImageElement) {
  const {width, height} = this
}

The parameter will be ignored when compiling to JavaScript.

See https://www.typescriptlang.org/docs/handbook/2/functions.html#declaring-this-in-a-function

CodePudding user response:

function onload(img){
  const {width, height} = img
}

Isn't onl oad passed the img?

  • Related