//var n=9; function f1(){ //n=99; function f2(){ var n=999; console.log(n); } return f2; } var result=f1(); result(); // 999 //先在f2中查找有没有变量n,再在f1中查找有没有变量n,最后在全局作用域中查找有没有变量n
看下面这几个例子就知道闭包的查找顺序了(其实就是根据函数的作用域链来查找)
var name="xiu"; var obj={ name:"xie", getName:function(){ return function(){ var name="baobao"; return name; } } } alert(obj.getName()());//baobao
var name="xiu"; var obj={ name:"xie", getName:function(){ return function(){ return name; } } } alert(obj.getName()());//xiu
var name="xiu"; var obj={ name:"xie", getName:function(){ return function(){ return this.name; } } } alert(obj.getName()());//xiu
var name="xiu"; var obj={ name:"xie", getName:function(){ var that = this; return function(){ return that.name; } } } alert(obj.getName()());//xie
时间: 2024-11-08 19:01:37