获取函数内部的变量

wiw*_*wit 4 javascript

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

示例代码

function a(){
  var sample = "hello world"
};
Run Code Online (Sandbox Code Playgroud)

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

sample2 = sample
console.log(sample2);
Run Code Online (Sandbox Code Playgroud)

当我 console.log sample2 然后 sample2 的值应该是“hello world”请分享您的知识我想在 javascript 中了解更多提前谢谢

小智 6

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

所以按照第一种方法,

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

var sample2 = a();
console.log(sample2); //This prints hello world
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用第二种方法,通过公开诸如

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
Run Code Online (Sandbox Code Playgroud)

希望这能解决您的疑问。