且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从JavaScript中的另一个函数调用变量

更新时间:2023-01-08 07:37:14

这里的问题是作用域之一,您(正确地)在函数作用域中声明了subsriptionId.但是,一旦该函数返回,该变量就会被GC处理(已收集垃圾).

The issue here is one of scopes, you're (rightly) declaring subsriptionId in a function scope. As soon as that function returns, though, that variable is GC'ed (Garbage Collected).

正如@GungFoo所说,起初,您可能会认为全局声明变量(因此永远不要使用var GC)会解决问题,并且起初会解决问题.但是很快您将污染全球范围,以至于您会遇到问题.例如,您可能无意中更改了另一个函数所依赖的变量的值.只需在Google上搜索几篇有关此事的文章,您很快就会发现为什么这不是一个好主意.

As @GungFoo said, at first, you might think that declaring the variable globally, (and thus never have the var GC'ed) would fix things, and it would, at first. But pretty soon you'll pollute the global scope to such an extend that you'll run into issues. You could, inadvertently, change the value of a variable on which another function relies, for example. Just google a few articles on the matter, you'll soon find out why this isn't a good idea.

一些替代方法:

假设其他功能" 是在全局范围内定义的,则可以为其分配一个属性:

Assuming the "other function" is defined in the global scope, you could assign it a property:

function()
{//this declares and assigns subscriptionId
    var subscriptionId = subscriptions[subscriptionIndex]["@metadata"]["@id"].substring(7);
    theOtherFunction.subscId = subscriptionId;//assign property
    alert(subscriptionId);
}
//the other one
function theOtherFunction()
{
    alert(theOtherFunction.subscId);//will alert the correct value
}

使用jQuery会更简单:

even simpler would be, simply to use the jQuery:

function theOtherFunction()
{
    var id = subscriptions[$("#subscriptionSelector").val()]["@metadata"]["@id"].substring(7);
    alert(id);//will work, too
}

后者的缺点是将在每次调用时扫描DOM,以找到该特定元素($("#subscriptionSelector")).要解决此问题,您可以使用闭包:

The downside of the latter being that the DOM will be scanned on each call, to find that particular element ($("#subscriptionSelector")). To fix that, you can use a closure:

var theOtherFunction = (function(selector)//takes DOM element as argument
{
    return function()//this is the actual function
    {//thanks to closures, selector will not be GC'ed
        var id = subscriptions[selector.val()]["@metadata"]["@id"].substring(7);
        alert(id);//works like a charm
    };
})($("#subscriptionSelector"))//pass DOM element as argument

最后一种方法乍一看似乎有些令人生畏,但要花一些时间来阅读IIFE,闭包和作用域向导.这是JS的***功能之一,非常强大,一旦掌握了基本概念也就不难了!

The last approach might seem a bit daunting at first, but spend some time reading up on IIFE, closures and scope wizardry. It's one of the best features of JS, very powerful, not that hard once you grasp the basic concepts, too!