Force typescript to put methods on the instance not the prototype

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

    It looks like this is a TypeScript/Knockout issue, as @Anzeo pointed out in his answer as well as your edit. I've gotten around the issue by putting my method declarations in the constructor but also using the var self = this; convention pointed out in the "Managing 'this'" section on Knockout's Computed Observable documentation. You TS code could look like this:

    class FooViewModel{
        FooAlert: KnockoutObservableAny;
        openFooAlertDialogueAdd: () => void;
    
        constructor(){
            var self = this;
            self.FooAlert = ko.observable();
            self.openFooAlertDialogueAdd = function(){
                self.FooAlert('whatever your FooAlert observable takes');
            };
        }
    }
    

    No matter what scope change might occur, the JavaScript closure around self keeps you from having to worry about this changing. That should solve both your problems.

提交回复
热议问题