简体   繁体   中英

Js: function and object scope /outside scope

I have an object like this

var Wheel = { //...function A, B etc.. here... }

how can I access an array value from a function A inside Wheel to the outside "root" of my javascript document?

PS. feel free to edit my title because i have no idea how to elaborate it. thanks

define the array in the global scope

var myarray;
var Wheel = { 
    a: function(){
        myarray = [1]; //new array
    }
}

//then you can acces myarray anywhere

Simply make the array a property of Wheel , eg

var Wheel = {
    arrayValue: [],
    A: function(a) {
        Wheel.arrayValue.push(a);
    }
}

Wheel.A(1);

Wheel.arrayValue; // [1]

Wheel.A(2);

Wheel.arrayValue; // [1,2]

So from your representation, A is a function, which means that objects declared within it are lost at the end of execution, due to their scope. A would be called like this:

Wheel.A();

At which point A would begin to execute the function and any variables declared within the scope of A, which were preceded by var, would be lost at the end of the call.

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