TypeScript - Accessing a variable in a inner object

945 Views Asked by At

I have a type script class which accepts a url (string) as parameter in the constructor. Inside the class, I have a another class which is the view model for a devextreme datagrid. The problem I am facing is I don't know how I can access the url property in a inner object (GridViewModel) which has a function as part of it.

export class MyClassOne {
    private myUrl: string;

    constructor(url: string) {
        this.myUrl = url;
    }

    public GridViewModel = {
        dataGridOptions: {
            dataSource : { store: someSource}
                   ...
            aFunction:  function(e){

                // this.myUrl is undefined
                var postUrl =  this.myUrl;               
            }             
        }
    }
}  
var myClassOne = new MyClassOne("https://www.google.com"); 

My question is, how do I access "this.myUrl" in the inner object function? Please help

Thanks,

2

There are 2 best solutions below

3
Franklin Pious On BEST ANSWER

the scope of 'this' has changed inside the function.Either u can create an arrow function which retains the scope or use a self variable to hold the outside scope.

eg of functions with arrow operator. Your function can be replaced as

e => {
var postUrl =  this.myUrl;              
}
0
Felix Cen On

So, basically I needed to replace function(e) with e=> to retain the scope of 'this'

export class MyClassOne {
    private myUrl: string;

    constructor(url: string) {
        this.myUrl = url;
    }

    public GridViewModel = {
        dataGridOptions: {
            dataSource : { store: someSource}
                   ...
            aFunction:  e => {

                // this.myUrl is undefined
                var postUrl =  this.myUrl;               
            }             
        }
    }
}

var myClassOne = new MyClassOne("https://www.google.com");