如何从外部,在jQuery函数内部获取变量? [英] How to get variables from the outside, inside a function in jQuery?

查看:1098
本文介绍了如何从外部,在jQuery函数内部获取变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何从函数的外部,jQuery的函数内部获取变量,但得到Uncaught ReferenceError: myvar is not defined.有什么办法吗?

I'm trying to figure out how can I get variables from the outside in a function, inside a function in jQuery but i get Uncaught ReferenceError: myvar is not defined. Is there any way of doing this?

我的代码的一个简单示例:

A simple example of my code:

$(function(){
    var myvar = "stackoverflow";
});

$(function(){
    alert(myvar);
});

但是当我在函数外部定义变量时,它会起作用:

But when I define the variable outside the function it works:

var myvar = "stackoverflow";

$(function(){
    alert(myvar);
});

为什么?

感谢您的帮助!谢谢!

推荐答案

第二个示例起作用的原因是因为您将myvar定义为全局变量(可从任何位置访问).

The reason the second example works is because you're defining myvar as a global variable (which is accessible from anywhere).

第一个示例不起作用,因为该变量是在功能范围内定义的(这意味着除该功能范围以及在该父功能范围内定义的功能范围之外,所有其他变量都无法访问该变量).

The first example doesn't work because the variable is defined within functional scope (meaning it's inaccessible from all except that function's scope, and the scope of functions defined within that parent function's scope).

如评论中所述,这就是JavaScript的工作方式.如果这是您遇到的问题,那么可能是时候重新考虑您的体系结构了.

As stated in the comments, this is just how JavaScript works. If this is a problem you're running into then it's probably time to rethink your architecture.

一种常见的模式是将 shared 变量定义为父对象或函数的属性.例如:

One common pattern is to define shared variables as properties of parent objects or functions. For example:

$(function() {
    var funcOne = function() {
        this.sharedVal = 'stack overflow';
    };
    var funcTwo = function() {
        console.log(funcOne.sharedVal);
    };
});

这样,您可以拥有不同的函数,这些函数可以与其他函数中的其他函数共享其属性,同时还可以保持全局名称空间的整洁.但是请注意,在此示例中,没有绑定为另一个函数的属性的简单var x = 'something';也可以.

This way you can have distinct functions that are able to share their properties from within other within other functions, whilst also keeping the global namespace clean. Note, however, that in this example, a simple var x = 'something'; which isn't bound as a property of another function would do just as well.

这篇关于如何从外部,在jQuery函数内部获取变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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