简体   繁体   中英

How can I access class properties which is imported in a function?

I'm trying to declare class variable in a function and access its properties in another function however I'm getting error 1120. Here's my code:

// function content
if (components == "settings")
{
    import DialogComponentsSettings;
    var dialogComponentsSettings:DialogComponentsSettings = new DialogComponentsSettings();
    addChild(dialogComponentsSettings);
    dialogComponentsSettings.init();
    back_mc.addChild(dialogComponentsSettings.settings_mc);

    dialogComponentsSettings.okBtn.addEventListener(MouseEvent.CLICK, onOkClick);
    dialogComponentsSettings.cancelBtn.addEventListener(MouseEvent.CLICK, onCancelClick);
}

private function onOkClick(e:MouseEvent):void
{
    var arr:Array = new Array();
    arr[0] = e.target.name;
    arr[1] = dialogComponentsSettings.cb.selected;
    arr[2] = dialogComponentsSettings.ns.value;
    arr[3] = dialogComponentsSettings.ta.text;
    dispatchEvent(new CustomEvent(CustomEvent.PASS_PARAMS, arr));
}

This is giving me error:

... \\PopupDialog.as, Line 129, Column 13 1120: Access of undefined property dialogComponentsSettings.

How can I fix this?

Your variable dialogComponentsSettings is a local variable of that function. It is unknown outside of that function. That's why you receive the error.

You should declare the variable outside the function. This way it is available in other functions as well.

Placing an import into an if block doesn't make too much sense: the if condition is evaluated at run time, the import statement at compile time.

Always place your imports at the beginning of your code. That makes it clear what imports are used and saves other developers trying to read your code the hassle of finding those deeply nested imports, somewhere hidden in your code.

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