我是一名 JavaScript 新手,正在尝试了解函数的工作原理。我发现了一个类似的问题here但它并没有真正回答我的问题。
以下面一段javascript为例
var test = function(){
console.log("kick off");
var insideTest = "variable inside test";
var init = function(){
var insideInit ="variable inside init";
console.log("inside init");
}
return{
init:init
}
}
test().init();
上面的代码打印如下:
kick off
inside init
但是如果我删除
return{
init:init
}
它给我一个错误提示
Uncaught TypeError: Cannot read property 'init' of undefined
此外,即使我使用 test().init()
调用 init 方法,如果 return 语句被删除,它也不会打印 inside Init
。
我的问题是为什么需要返回init:init
来执行init方法。
编辑: 在这里回答为什么我的 init 函数在 test() 函数内部是我正在尝试做的事情的更大图景。
var test = function() {
var init = function() {
var a = 0;
function1();
function2();
}
var function1() = function() {
//some code
}
var function1() = function() {
//some code
}
return {
init: init
}
}
最佳答案
已添加内联评论。此外,test
中的 init
将可以访问在其 (init) 作用域之外定义的变量,即闭包。 test
正在返回一个对象来访问它的内部函数。这个特定的模式是revealing module pattern
var test = function(){
console.log("kick off");
var insideTest = "variable inside test";
// Here init is a function which is private to test function
// Any function calling test will not have access to init unless it is 'exposed'
var init = function(){
var insideInit ="variable inside init";
console.log("inside init");
}
return{
init:init // exposing the private function
}
}
关于javascript - 为什么我需要返回 "init"来执行init函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43929098/