简体   繁体   中英

How can I access a class variable inside a class function?

I have the following code where I tried to replace createModal with a class called Modal. However when I tried this typescript gives me errors and says that "link does not exist in the current scope":

module Admin.MyAccount.Access {

    export function createModal(link: Link) {
        link.Modal.$Modal = $.modal({
            resizeOnLoad: true
        });
        link.Modal.$Modal.applyTemplateSetup()
    }

    export class Modal {
        link: Link;
        constructor (link: Link) {
            this.link = link;
        }
        create() {
            link.Modal.$Modal = $.modal({      // < Error here
                resizeOnLoad: true
            });
            link.Modal.$Modal.applyTemplateSetup() // < Error here
        }

    }

}

When I am using the function I call the function like this:

        createModal(link);

Am I doing something wrong here? Why is it that I cannot access link inside of the create() ? Also could I do this with a static function. Would that be easier as I would not have to call the new to make a new instance of Modal ?

You will need to add this to the call, since you need to access the class scope.


As far as choosing wether or not to use static comes down to how you use the object. Do you have multiple instances of the object, but only always needs 1 copy of it? If so, use static .

This means that all of your modal's will be linked together, and there can always only be one.

Using static in javascript

a static function ( that is there is only one copy of the function no matter how many objects you create) can be real handy for utility functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM