您如何在使用JavaScript创建的自定义对象之外引用其自定义对象? [英] How do you reference a custom object outside of the function it was created in with JavaScript?

查看:112
本文介绍了您如何在使用JavaScript创建的自定义对象之外引用其自定义对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用JavaScript和jQuery.

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.

但是,如果在主JQuery ready函数内部创建子函数,则可以将对象创建为ready函数的局部变量,并在其他函数中使用它们.

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.

类似这样的东西:

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

这篇关于您如何在使用JavaScript创建的自定义对象之外引用其自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆