从Javascript方法返回全局变量 [英] Return Global Variable from Javascript Method

查看:160
本文介绍了从Javascript方法返回全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法:

  function calculateThings(newdata){


}

如何从里面返回一个全局变量?



谢谢!

遗憾的是没有详细说明。

  var thisData =; 

函数calculateThings(newData){

thisData = newData.things.otherthings //值为10;



alert(thisData)//不返回

我做错了什么?

解决方案

在返回全局变量时似乎并没有多少意义,该函数可以设置它并引用其他函数。

  var setGlobal =(function(global){
return函数(值){
global.someVarName = value;
}
}(this));

var readGlobal =(function(global){
return function(){
return global.someVarName;
}
}(this));

setGlobal('foo');
alert(readGlobal()); // foo
alert(someVarName); // foo


I have a method:

function calculateThings(newdata){


}

How do I return a global variable from within it?

Thanks!

Sorry for the lack of detail.

var thisData = "";

function calculateThings(newData) {

    thisData = newData.things.otherthings //has a value of 10;

}

alert(thisData) //returns nothing

What am I doing wrong?

解决方案

There doesn't seem to be much point in returning a global variable, the function can just set it and other functions reference it.

var setGlobal = (function(global) {
  return function(value) {
    global.someVarName = value;
  }
}(this));

var readGlobal = (function(global) {
  return function() {
    return global.someVarName;
  }
}(this));

setGlobal('foo');
alert(readGlobal()); // foo
alert(someVarName);  // foo

这篇关于从Javascript方法返回全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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