Welcome Guest. Sign in or Signup

0 Comments

How to create instance methods in TS (rather than prototypes)?

Asked by: 3859 views 5.TypeScript

+2
0

If you define a function like this in JS, it would be an instance method:


function MyClass() {
    this.getExample = function() {
    alert("Example");
    }
}
‚Äč

However, when you do the same in TS, compiling it to JS will convert it to a prototype function, which might not be always preferrable. So, to instead prevent the function from becoming a prototype, do this in TS to keep it a instance-method:


class MyClass {
    getExample: any;
    constructor() {
        var example = function () {
            alert("Example");
        }
        this.getExample = example;
    }
}

Comments on Question