简体   繁体   中英

Access JavaScript “this” from TypeScript

I'm currently working with the AlpacaJS library within my typescript project. This JavaScript/JQuery library is included in my Typescript class and wants me to pass some options in a json style object like so:

this.options = {
    "collapsible": false,
    "fields": {
        "id": {
            "events": {
                "change": function () {
                    console.log(this.getValue());
                }
            }
        }
    }
};

Passing this object i say: add a change event to the field "id" within the form which alpaca generates. Using "this" within that function gives me the "this" of the library, and NOT the typescript class "this".

The problem : What if i like to call a method or variable within my Typescript class? I would have to use "this", but "this" is binded to the alpaca/javascript this. I can't change it to (event) => { ... } or { ...}.bind(this) because that way i CAN access the typescript "this", but i CAN'T access the alpaca/javascript this, i need both of them....

i CAN'T access the alpaca/javascript this, i need both of them

Use the standard javascript trick of capturing this before creating the function:

let _self = this;
this.options = {
    "collapsible": false,
    "fields": {
        "id": {
            "events": {
                "change": function () {
                    console.log(_self.getValue());  // the class instance
                    console.log(this); // the lib version 
                }
            }
        }
    }
};

This tip is documented here as well : https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

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