我试图通过返回外部函数在初始化时调用javascript对象外部的另一个函数
为什么这不起作用?我试图调用内部函数“refreshPage” 这将起作用:我试图通过返回外部函数在初始化时调用javascript对象外部的另一个函数,javascript,function,object,return,Javascript,Function,Object,Return,为什么这不起作用?我试图调用内部函数“refreshPage” 这将起作用: var myFunc = function(){ var refreshPage = function(){ alert("hello"); }; return { refreshPage: refreshPage }; }(); function refreshPage(){ return myFunc.refreshPage(); } refreshPage();
var myFunc = function(){
var refreshPage = function(){
alert("hello");
};
return {
refreshPage: refreshPage
};
}();
function refreshPage(){
return myFunc.refreshPage();
}
refreshPage();
我认为如果我们重新命名和重新定位一些东西,问题会更清楚
/* sayHello will be a function: */
function sayHello() {
alert("hello");
}
/* makeObjectWithMethod will be a function: */
function makeObjectWithMethod() {
/* equivalently, assign sayHello to the variable refreshPage, but don't invoke */
var refreshPage = sayHello;
/* return an *object* with a property, refreshPage, whose value is the function */
/* sayHello - not the value it returns, but the function itself. */
return {
refreshPage: refreshPage
};
}
/* make a variable called myFunc whose value is the object returned by above */
var myFunc = makeObjectWithMethod();
/* make a method called finallyReallyDoIt that *when invoked*, calls a method */
/* of myFunc named refreshPage */
function finallyReallyDoIt() {
return myFunc.refreshPage();
}
如果您从未调用
finallyReallyDoIt
,您所做的就是创建myFunc
对象并将finallyReallyDoIt
声明为函数。就像上面的sayHello
和makeObjectWithMethod
一样,finallyReallyDoIt
在调用它之前不会发生。您需要调用refreshPage()代码>我也使用返回{refreshPage:refreshPage};为什么这不起作用?但是您正在一个未调用的函数refreshPage
中调用它。我想,添加空括号就是调用它。谢谢。现在更有意义了。
/* sayHello will be a function: */
function sayHello() {
alert("hello");
}
/* makeObjectWithMethod will be a function: */
function makeObjectWithMethod() {
/* equivalently, assign sayHello to the variable refreshPage, but don't invoke */
var refreshPage = sayHello;
/* return an *object* with a property, refreshPage, whose value is the function */
/* sayHello - not the value it returns, but the function itself. */
return {
refreshPage: refreshPage
};
}
/* make a variable called myFunc whose value is the object returned by above */
var myFunc = makeObjectWithMethod();
/* make a method called finallyReallyDoIt that *when invoked*, calls a method */
/* of myFunc named refreshPage */
function finallyReallyDoIt() {
return myFunc.refreshPage();
}