var name = "world";
(function(){
if(typeof name ==="undefined"){
var name="jack";
console.log("Goodbye"+name);
}else{
console.log("hello"+name)
}
})()
function fun(n,o){
console.log(o);
return {
fun:function(m){
return fun(m,n);
}
}
}
var a=fun(0);
a.fun(1);
a.fun(2);
a.fun(3);
这是两个js面试题?谁能帮我解答一下,并告诉原理
第一道题会输出Goodbyejack,在匿名自调函数中定义了name变量,因为声明提前,所以执行typeof时name为undefined
第二题,在执行var a=fun(0)时,输出undefined,因为只传了一个参数,n=0,o=undefined,并返回fun对象
执行a.fun(1)时,又递归调用外层的fun函数,即fun(1,0),m为1,n为0,故输出0;剩下的同理
第一题看这个:javascript运行机制
第二个设计闭包,具体看#2的
javascript的基础教程里都有实例,多看看基础吧