js面试必考之作用域和闭包
作用域介绍
先来看下作用域,看张图片:
自由变量
一个变量在当前作用域没有定义,但被使用了
向上级作用域一层一层的去寻找,直到找到为止
如果到全局作用域还没找到,则报错xxx is not defined
这里面有三个函数,每个函数中都定义这一个变量,a1它的作用域范围是最大红色方框,a2的作用域为中间的方框,a3的作用域为最里面的方框,而在fn3函数 return语句 返回a+a1+a2+a3是,a ,a1,a2,这三个变量在fn3中没有,那么他们三个就按照自由变量的方式向上级作用域一层一层的去寻找,直到找到为止。
闭包介绍
作用域应用的特殊情况,有两种表现:
函数作为参数被传递
函数作为返回值被传递
//函数作为返回值
function create(){
let a1=100;
return function(){
console.log(a1);
}
}
let fn1=create();
let a1=200;
fn1();
//函数作为参数
function printf(){
let a=200;
fn()
}
let a=100;
function fn(){
console.log(a)
}
printf(fn);
this
this的用法一般有六种用法
1作为普通函数
2使用call apply bind
3作为对象方法被的调用
4在class方法中调用
5箭头函数调用
6原型中的this
function fn2(){
console.log(this);
}
fn2()//普通函数 window
fn2.call({x:100});//{x:100}
const fn3=fn2.bind({x:200});
fn3()//{x:200}
//另外关于this在前4 种可以记住,this是谁调用this,this就指向谁,但在箭头函数却不是这样
关于第六点,我们就以我们上篇博客中的xialuo为例子进行说明
我们如果输出xialuo._ proto_.sayHi() 返回的是 姓名 undefined 学号 undefined,但是我们xialuo._ proto _.sayHi.call(xialuo)就能显示出值了
箭头函数:
函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
const zhangsan={
name:'张三',
sayHi(){
//this即当前对象
console.log(this);
},
wait(){
setTimeout(function(){
console.log(this)
})//window 作为普通函数
},
waitAgain(){
setTimeout(()=>{
console.log(this);//当前对象 箭头函数的this是取上级对象的this
})
}
}
var str="window";
const obj={
str:"obj",
f1:
function () {
console.log(this.str+'qqq');
return {
str:'new',
ff:()=>{
console.log(this.str+'ccc');
}
}
}
}
var ne=obj.f1();
ne.ff();
手写bind函数
fn7的原型是没有bind的,但是由于fn7._ proto _===Function.prototype,
而Function.prototype里面存在bind。
Function.prototype.bind1=function (){
//将参数拆解为数组
const args=Array.prototype.slice.call(arguments);
//获取this
const t=args.shift();
console.log(this);
const self = this;//保存fn7.bind(...)中的this
//返回一个函数
return function (){
console.log(self.apply(t,args));
return self.apply(t,args);
}
}
function fn7(a,b,c){
console.log('this:',this);
console.log(a,b,c);
return 'this is fn7'
}
const ffn1=fn7.bind1({x:100},10,20,30)()
console.log(ffn1);
console.log(ffn1);
const res=ffn1();
console.log(res);
实际开发中闭包的应用
//1隐藏数据
function createCache(){
const data={}
return{//此处就为闭包
set :function(key,val){
data[key]=val
},
get: function(key){
return data[key]
}
}
}
const c=createCache()
c.set('a',100)
console.log(c.get('a'))