获取函数内部的变量

新手上路,请多包涵

你好我是 javascript 的新手 我只想问一下是否有可能在函数中获取值?

示例代码

function a(){
  var sample = "hello world"
};

然后我将转到全局上下文并获取变量 sample

 sample2 = sample
console.log(sample2);

当我 console.log sample2 那么 sample2 的值应该是“hello world”请分享你的知识我想在 javascript 中学习更多提前谢谢

原文由 wiwit 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 367
2 个回答

与任何其他编程语言一样,您需要做的就是返回您需要访问的值。所以要么你可以让你的函数返回变量值,这样你就可以访问它。或者让它返回一个对象,该对象还具有可以返回值的子函数

所以按照第一种方法,

 function a() {
    var sample = "hello world";
    return sample;
}

var sample2 = a();
console.log(sample2); //This prints hello world

或者,您可以使用第二种方法,您可以通过公开辅助函数来更改私有变量,例如

function a() {
    var sample = "hello world";
    return {
        get : function () {
            return sample;
        },
        set : function (val) {
            sample = val;
        }
    }
}

//Now you can call the get function and set function separately
var sample2 = new a();
console.log(sample2.get()); // This prints hello world

sample2.set('Force is within you'); //This alters the value of private variable sample

console.log(sample2.get()); // This prints Force is within you

希望这能解决你的疑问。

原文由 Akhil Arjun 发布,翻译遵循 CC BY-SA 3.0 许可协议

有很多方法可以做到这一点,到目前为止最好的方法是在函数外声明变量,然后在函数内分配它们。

 var sample;
var myname;

function a() {
    sample = "Hello World";
    myname = "Solly M";
}

console.log(sample);
console.log(myname);

原文由 RealSollyM 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题