Home > Article > Web Front-end > How to solve the problem of undefined function when JS parent function calls child function
Firstly, I define a global function Locating, and then define a local function pageScroll within Locating. Then when my global function calls pageScroll, I get the error Uncaught ReferenceError: pageScroll is not defined.
The code is as follows:
function Locating(locate,time){ console.log(locate+' -- '+time); var p_locate=document.getElementById(locate); var window_top_y = document.body.scrollTop;//获取滚动条顶部距离页面顶部的距离 var element_top_y = p_locate.offsetTop;//获取某元素顶部距离页面顶部的距离 var distance = window_top_y-element_top_y;//当前窗口与顶部的距离 var time = time; var move_distance = time>50?Math.ceil((distance/Math.ceil(time/50))):distance;//每次移动的距离 //每次移动的位移应为distance/duration,要移动的位置为element_top_y, function pageScroll() { var top = document.body.scrollTop;//获取滚动条顶部距离页面顶部的距离 var dis_top = top - element_top_y; window.scrollBy(0,-move_distance); scrolldelay=setTimeout('pageScroll()',50); if(dis_top<=0){ clearTimeout(scrolldelay); } // console.log(dis_top); } pageScroll(); }
At first I thought it was a scope chain problem.
But the code with the same structure below does not execute the error
##
function a(){ console.log("a") function b() { console.log("b") } b() }Go to the forum and ask. It turns out that the reason for calling setTimeout
steTimeout function mechanism is to use eval to execute the first parameter 'action()" string. Since the action() string does not exist, Then I changed it to an object action for testing.
#It turns out that after setTimeout is executed, the execution environment automatically switches to the window environment, so pageScroll is called again () will cause an undefined function error.
##The solution is to writesetTimeout('pageScroll()',50)
##.
#
setTimeout(pageScroll,50);That is, write the string as an object.
It seems that when setIntraval is executed, the environment will also be switched to the window object.
The above is the detailed content of How to solve the problem of undefined function when JS parent function calls child function. For more information, please follow other related articles on the PHP Chinese website!