其他答案已经充分涵盖了对象语法并在范围内调用函数。正如我在评论中提到的,你可以这样做:
function outer(){
(function () {
var c = "inner";
console.log(c)
})();
}
window.outer();
它记录inner
得很好。
编辑:原始代码示例中的私有/隐藏变量innerFct
也可以在闭包中捕获。
outer = function() {
var innerFct = function () { console.log("inner"); }
// innerFct is captured in the closure of the following functions
// so it is defined within the scope of those functions, when they are called
// even though it isn't defined before or after they complete
window.wrapper = function() { innerFct(); }
return function() { innerFct(); }
}
outer();
// each of these next three lines logs "inner"
window.wrapper(); // assigned to global variable
outer()(); // calling the returned function
var innerFctBackFromTheDead = outer(); // saving the returned function
innerFctBackFromTheDead();
还有对象构造函数/原型语法。
function Outer() {
this.inner = function() {
this.c = "inner";
console.log(this.c);
}
}
var out = new Outer();
out.c; // undefined
out.inner(); // logs "inner"
out.c; // "inner"
有关新关键字和原型的更多信息:http: //pivotallabs.com/javascript-constructors-prototypes-and-the-new-keyword/