Force typescript to put methods on the instance not the prototype

后端 未结 3 798
遇见更好的自我
遇见更好的自我 2021-02-14 12:39

Is it possible to force typescript to put methods on the instance not the prototype. I ask this because I frequently have \"this\" scope issues which having methods on the proto

3条回答
  •  故里飘歌
    2021-02-14 12:59

    If you're having scope issues I feel bad for you son, I've got 99 problems but this ain't one!

    Steve's answers show the correct way to define class methods, methods that will be exposed on each instance. However, if you're encountering scope issues, this is probably due to the fact you're calling those methods from another context.

    For example, if you're using Knockout and you bind one of those methods to a click binding, Knockout will override the scope to the current scope of the binding, NOT the scope you have defined the method on.

    There are two options to prevent this loss of scope.

    Firstly you can define your methods in the constructor, to expose them on the instance instead of on the prototype.

    Like:

    class Greeter {
        greet:() => string;
        greeting: string;
    
        constructor(message: string) {
            this.greeting = message;
            this.greet = () => {
                return "Hello, " + this.greeting;
            }
        }
    

    Secondly, you could use the => syntax to scope your class methods.

    Example:

    class Greeter {
        greeting: string;
        constructor() {
            this.greeting: "Blabla";
        }
        greet= () => {
            alert(this.greeting);
        }
    }
    

提交回复
热议问题