简体   繁体   中英

How do you reference a custom object outside of the function it was created in with JavaScript?

I'm currently using JavaScript and jQuery.

I have an function which executes once the document is ready, and inside that I am creating objects which contain various attributes.

Within the same function, I can access these new object's attributes no problem, however once I'm inside a different function I can't seem to reference them properly and therefore cannot access the objects or the information inside them.

What's the correct way to reference the attributes of an object which was created in a different function to the one looking for the information?

In general you can't reference an object that was created in a different function. The scoping rules do not allow that.

However, if you create your sub functions inside of the main JQuery ready function, you can create your objects as local variables to the ready function and use them in your other functions.

This would create a closure allowing the variables to still exist yet not be in the global scope.

Something like this:

$(function () {
    var MyObj = {"CT":0};
    function Inc(){
      MyObj.Ct++;
    }
    $("INPUT[type=button]").click(Inc);
})

Create the a global refernence to the object outside of the function, eg:

var obj;

function func1()
{
   obj = 1;
}

function func2()
{
   alert(obj);
}

The best way would be to create a global object which holds all that data.

var myGlobalData = function(){
    // private data
    var some = 'data',
        foo  = 'bar';

    // public
    return {
        publicfunction: function(){
           alert(foo);
           return(some);
        }
    }      
};

within your ready code you can create an instance of that

$(document).ready(function(){
     var myData = new myGlobalData();
     myData.publicfunction();
});

Note that in this example, you can't access 'some' and 'foo' with

myData.foo = 'bar'; // not possible

because those are 'private' to the object. If you write an object in that manner, you can simulate a more OOP style.

I have an function which executes once the document is ready, and inside that I am creating objects which contain various attributes.

Define these objects as properties of the global object ( window ) and you'll be fine.

function onready() {
  window.myObject = {};
}

function otherFunction() {
  window.myObject.fu = "bar";
}

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