系列文章目录
目录
前言
JS基础知识
一、作用域
- 全局作用域
- 函数作用域
- 块级作用域(ES6新增)
// ES6 块级作用域 {}里面使用变量
if(true) {
let x = 100;
}
console.log(x); // 报错
二、自由变量
- 一个变量在当前作用没有定义,但被使用了
- 向上级作用域,一层一层依次寻找,直至找到为止
- 如果到全局作用域都没找到,则报错 xx is not defined
三、闭包
作用域应用的特殊情况,有两种表现:
- 函数作为参数被传递
- 函数作为返回值被返回
// 函数作为返回值
function create() {
let a = 100;
return function() {
console.log(a)
}
}
const fn = create();
const a = 200;
fn() // 100
// 函数作为参数
function print(fn) {
let a = 200;
fn();
}
let a = 100;
function fn() {
console.log(a);
}
print(fn) //100
// 所有的自由变量的查找,是在函数定义的地方,向上级作用域查找
// 不是在执行的地方!!!
// 闭包隐藏数据,只提供 API
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'));
四、this
- 作为普通函数
- 使用 call apply bind
- 作为对象方法被调用
- 在 class 方法中调用
- 箭头函数
五、手写bind函数
Function.prototype.bind1 = function() {
// 将参数解析为数组
const args = Array.prototype.slice.call(arguments);
// 获取 this(取出数组第一项,数组剩余的就是传递的参数)
const t = args.shift();
const self = this; // 当前函数
// 返回一个函数
return function() {
// 执行原函数,并返回结果
return self.apply(t, args);
}
}
总结
以上是JS作用域、自由变量、闭包、this学习笔记。