JS作用域
作用域是在运行时代码中的某些特定部分中变量,函数和对象的可访问性
全局作用域:var
函数作用域:function
块级作用域:let,const ES6新增
JS自由变量
当一个变量在当前作用域没有定义,但是被使用,就会向上一层一层的作用域寻找,直到找到为止。
所有的自由变量的查找,是在函数定义的地方,向上级作用域查找,不是执行的地方
若全局作用域下也没有,则会报错xx is not defined
JS闭包
JS作用域两种特殊应用:
- function作为返回值
function fn (){
return fn1()
}
- function作为参数传递
function print (fn){
fn()
}
function fn1 (){
return 2
}
print(fn1)
JS中this指向
this的指向是在执行的时候确定的,不是在定义的时候确定的
手写bind函数
- bind函数运用
function fn(a, b, c) {
console.log('this', this);
console.log(a, b, c);
return 'this is fn'
}
//bind用法:bind(this,参数1,参数2,参数3...)
//bind(this,agu)
const fn1 = fn.bind({ x: 100 }, 1, 2, 3)
const result = fn1()
console.log(result);
console.log(fn.__proto__ === Function.prototype);//true
- 模拟 bind
Function.prototype.bind1=function(){
//将参数拆解为数组
const args = Array.prototype.slice.call(arguments)
//获取this(数组第一项) 截取第一项后,将后面的项返回成一个新的数组
const t =args.shift()
const self =this
return function (){
//apply用法:apply(this,[参数1,参数2,参数3...])
return self.apply(t,args)
}
}
const fn1 = fn.bind1({ x: 100 }, 1, 2, 3)
const result = fn1()
console.log(result);
- bind函数应用:闭包隐藏数据,只提供API
//模拟缓存
function createChace() {
const data = {}
return {
set: function (key, value) {
data[key] = value
},
get: function (key) {
return data[key]
},
}
}
const c = createChace()
c.set('a', 100)
console.log(c.get('a'));