Force typescript to put methods on the instance not the prototype

后端 未结 3 785
遇见更好的自我
遇见更好的自我 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:43

    The methods on the prototype are the methods that are available on each instance.

    class Example {
        constructor(private someProperty: string) {
    
        }
    
        method() {
            return this.someProperty;
        }
    }
    
    var exampleA = new Example('A');
    var exampleB = new Example('B');
    var exampleC = new Example('C');
    
    console.log(exampleA.method()); // A
    console.log(exampleB.method()); // B
    console.log(exampleC.method()); // C
    

    Each instance will have the someProperty and method() copied to its prototype. You can check this using:

    alert(exampleC.hasOwnProperty('someProperty') ? 'Yes' : 'No');
    

    It is only when the instance doesn't have its own property that JavaScript will walk up any dependency chain to find the property on a class higher up the dependency chain.

    If you supply the code where you are having trouble with the scope of this I'm sure we can help you to fix it.

提交回复
热议问题