0

I want to define a class in JavaScript (TypeScript) that one of its properties (indentListView) is an instance of an external class. For defining the inner class instance, I want to access the outer class property (Selector.modalPanel). How can I do this?

export class Selector {
    indentListView  // the inner class instance
    modalPanel // the property I wanna access

    constructor(SelectorItems) {

        this.indentListView = new SelectListView({

            didCancelSelection() {
                Selector.modalPanel.hide()   // using `this` here refers to SelectListView instead of Selector 
                return {}
            },

        })

        this.modalPanel = atom.workspace.addModalPanel({
            item: this.indentListView
        })
    }
}

I cannot use this when I am initiating the inner class because of scoping issues.

Amin Ya
  • 1,515
  • 1
  • 19
  • 30
  • You *can* use `this`, you just need to fix the scoping there - use an arrow function instead of a method – CertainPerformance Mar 22 '20 at 00:42
  • The question you give me is for a function. I am talking about classes and initiating inner class. I cannot use arrow functions. Please open the question – Amin Ya Mar 22 '20 at 00:44
  • 1
    Your `didCancelSelection() {` is a method, which is the same as a function in all respects that matter here. The method described in the linked question and in my comment above *will* fix the problem. If you aren't allowed to use an arrow function for some strange reason, you can use `.bind`, or `that = this` - see the linked question – CertainPerformance Mar 22 '20 at 00:45
  • (`Selector.modalPanel.hide()` doesn't work because `modalPanel` is a property of the instance, not a property of the constructor) – CertainPerformance Mar 22 '20 at 00:46
  • How can I define `didCancelSelection` using arrow functions? I am allowed, but I don't see the way to do that. – Amin Ya Mar 22 '20 at 00:49
  • You defined `didCancelSelection() {` using method syntax - you just need to use an arrow function instead, and then referencing `this` will work as you want it to – CertainPerformance Mar 22 '20 at 00:49
  • using ` didCancelSelection = () => { this.modalPanel.hide() return {} },` breaks my script totally – Amin Ya Mar 22 '20 at 00:52
  • 1
    You need to use colons to separate a key from a property value, not `=`s - eg `{ foo: 'bar' }`, not `{ foo = 'bar' }` – CertainPerformance Mar 22 '20 at 00:53

0 Answers0