我已尝试在函数外声明变量,但我得到了未定义。
function scope() {
let foo = 1;
const bar = function() {
return ++foo;
}
return bar;
}
const baz = scope();
console.log(baz.foo);
console.log(baz.foo);
答案 0 :(得分:1)
这是一种方法,模块模式:
var Module = (function () {
//empty object
var my = {};
//value
my.value = 1;
//method for incrementing the value
my.increment = function () {
this.value++;
};
return my;
}());
Module.increment(); //increment the value from outside
console.log(Module.value) //log the new value
jsfiddle:https://jsfiddle.net/9dr9xy23/5/