Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

TypeScript: Cannot reference public things in static member

I am trying to call a public member function from a static variable this so typescript:

class myClass {
    static myTmp: myClass;

    constructor(elem: HTMLElement) {
        elem.addEventListener(“mousedown”, this.callThis);
    }
    public setTmp() {
        myClass.myTmp = this;
    }
    public callThis() {
        myClass.myTmp.myMethod();
    }
    public myMethod() {
        console.log("Hello World!");
    }
}

But I keep getting myClass.myTmp.myMethod is not a function. This example may seem weird, but it makes sense in my real problem. I have tried doing it through a global variable as well, but still no luck. I would like to keep it all within one class. Am I missing something major here?

EDIT: This is what I was trying to do, and this works:

class myClass {
    static myTmp?: myClass;

    constructor(elem: HTMLElement) {
        elem.addEventListener(“mousedown”, this.callThis.bind(this));
    }
    public setTmp() {
        myClass.myTmp = this;
    }
    public callThis() {
        myClass.myTmp?.myMethod();
    }
    public myMethod() {
        console.log("Hello World!");
    }
}

I then have a list of myClass'es and at some point "setTmp" is called, enabling the "myMethod" method.

question from:https://stackoverflow.com/questions/65541343/typescript-cannot-reference-public-things-in-static-member

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

why don't you simply use arrow functions?

elem.addEventListener('mousedown', () => this.callThis());

changing it to this code will work. You don't need to be using the .bind at all :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...