文章目录
一、防抖debounce
防抖:就是方式高频触发,导致的一系列问题,例如当我们添加鼠标的移动事件,频繁触发导致事件的回调有时候执行的时间会导致页面卡死的问题,又或者input输入,发送请求,我们可以设定一个时间,在这个事件内多次触发,会清空时间,直到没有触发的时候才会去发送请求。
//防抖 debounce
function debounce(fn){
let timer = null;
return function(){
clearTimeout(timer);
timer = setTimeout(()=>{
fn.apply(this,arguments);
},500)
}
}
function sayHi(){
console.log('防抖触发')
}
let ipt = document.querySelector('.input');
console.log(ipt);
ipt.addEventListener('input',debounce(sayHi))//使用防抖函数
二、节流throttle
节流:设置一个时间,当触发这个事件的时候,这个时间内不会被再次触发,只会在这个时间周期触发。
//节流 throttle
function throttle(fn){
let canRun = true;
return function(){
if(!canRun) return;
canRun = false;
//设置定时器
setTimeout(()=>{
fn.apply(this,arguments);
canRun = true;
},500)
}
}
function sayHello(){
console.log('触发节流');
}
let tt = document.querySelector('.input');
console.log(tt);
window.addEventListener('resize',throttle(sayHello));
三、函数柯里化
函数柯里化指的是将能够接收多个参数的函数转化为接收单一参数的函数,并且返回接收余下参数且返回结果的新函数的技术。
函数柯里化的主要作用和特点就是参数复用、提前返回和延迟执行。
在一个函数中,首先填充几个参数,然后再返回一个新的函数的技术,称为函数的柯里化。通常可用于在不侵入函数的前提下,为函数 预置通用参数,供多次重复调用。
简单案例展示
add(1)(2)(3) = 6;
function add(x,y,z){
return x + y + z;
}
//通过柯里化实现
const currying = function(fn){
return function(x){
return function(y){
return function(z){
return fn(x,y,z);
}
}
}
}
实现通用柯里化:
var currying = function(fn){
//curryFun作用:就是一个递归函数,根据函数参数的长度来判断递归的次数,生成return function(){}个数
//原来一直有一个误区:就是觉得返回的return function(){}一定得有对应的参数,其实不用,因为他是根据传入的形参来执行的,(是个闭包的形式,只在最后一步的时候才有用。)
return function curryFun(...args){
if(args.length<fn.length){
return function(){
//每一次返回的参数都会被累加到一起:x--->x,y-->x,y,z当最后一次执行时说明参数已经使用完了
return curryFun(...args,...arguments);
}
}else{
return fn(...args);
}
}
}
//使用柯里化,方便我们更好地理解
function addNum(pre,num,pig){
return pre + '-' + num + '@' + pig
}
let result = currying(addNum)('hahah');
console.log(result('didi')('fuck'));
console.log(result('meimei',1))
意义:
参数复用:
let str1 = '111111111';
let str2 = '222222222';
function addPre(pre,str){
return pre +'-' + str;
}
let pre = "AA";
console.log(addPre(pre,str1));
console.log(addPre(pre,str2));
根据上面的需求我们知道要复用pre,这个时候可以通过curry柯里化来实现:
let addPreFn = function currying(addPre)(pre);
console.log(addPreFn(str1));
console.log(addPreFn(str2));
延迟执行:
function getAjax(){
let xhr;
if(XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject();
}
return xhr;
}
//上面这个形式在判断兼容性的时候就做初始化了,这种方式不是很节约性能。
改变上面的形式:
function getAjax(url,method){
if(XMLHttpRequest){
return function(){
return new XMLHttpRequest();
}
}else{
return function(){
return new ActiveXObject();
}
}
}
let myGetAjax = curry(getAjax('api/users'));
let xhr = myGetAjax('get');
console.log(xhr());//执行
四、组合(composion)和管道(pipe)
组合就是我们把两个或者多个函数封装到一起执行的方法。(也可以称为无值变成,合成运算过程)我们来看下面的代码:
管道跟组合一样只不过,管道是从左至右执行。组合是从右至左执行的。
function aFn(num){
return num + 10;
}
function bFn(num){
return num * 2;
}
//上面这两个函数,我们都必须要传入一个值,来调用。我们可以通过无值得方式来实现上面的过程:就是我们所说的组合方法
//组合方式实现上面的方法
const compose = function(bFn,aFn){
return function(num){
return bFn(aFn(num));
}
}
//调用也很重要,我们来看如何调用:
let myFn = compose(bFn,aFn);
let res = myFn(5);
cosole.log(res);//30;
通过上面管道的方式我们可以发现:组合的函数执行是从右至左的方式传递和执行的
通用组合的封装:
const compose = function(...fns){
return function(arg){
//reduce方法只提供参数,第一个和第二个参数,至于怎么处理这个参数是根据reduce里面的方式来进行的,然后reduce返回的结果会是累加的过程。
//因为是从右往左执行的所以需要reverse一下。
return fns.reverse().reduce((acc,fn)=>{
return fn(acc);
},arg)
}
}
案例:
const str = '加快福,京东方接口。的看法尽快答复。';
//获取句号
const getPeriod = str=>str.match(/。/g);
//获取长度
const getLength = str=>str.length;
//判断奇偶
const oddOrEven = num =>num%2 ===0? '偶数':'奇数';
const formatStr = compose(oddOrEven,getLength,getPeriod);
console.log(formarStr(str));
五、响应式原理
我们下来自定义实现一个vue响应式的过程
第一次渲染:
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./kvue.js"></script>
</head>
<body>
<div id="app">
<div>111</div>
{{message}}
</div>
<script>
let vm = new Kvue({
el:'#app',
data:{
message:'数据'
}
})
</script>
</body>
</html>
//kvue.js
class Kvue{
constructor(options){
this.$options = options;
this._data = options.data;
this.compile();
}
compile(){
let ele = document.querySelector(this.$options.el);
let childNodes = ele.childNodes
childNodes.forEach(item=>{
if(item.nodeType === 1){
//元素节点
}else if(item.nodeType === 3){
//文本节点
// [^{}\s] :表示不能存在{}和空格
let reg = /\{\{\s*([^{}\s]+)\s*\}\}/g
let textContent = item.textContent;
if(reg.test(textContent)){
let $1 = RegExp.$1;
//正则匹配里面的replace方法
item.textContent = item.textContent.replace(reg,this._data[$1]);
}
}
})
}
}
修改成响应式:
响应式的过程是:1、数据被修改(数据观察,数据劫持) 2、视图更新(观察者模式);vue2是通过发布订阅模式实现的
1.第一种实现方式:观察者模式
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./kvue.js"></script>
</head>
<body>
<div id="app">
<div>111</div>
{{message}}
</div>
<script>
let vm = new Kvue({
el:'#app',
data:{
message:'数据'
}
});
setTimeout(()=>{
vm._data.message = '我修改了数据'
},1000)
</script>
</body>
</html>
//kvue.js
class Kvue extends EventTarget{
constructor(options){
super();
this.$options = options;
this._data = options.data;
this.observe(this._data);
this.compile();
}
observe(data){
let keys = Object.keys(data);
let _this = this;
keys.forEach(key=>{
let value = data[key];
Object.defineProperty(data,key,{
configurable:true,
emumerable:true,
get(){
console.log('get');
return value;
},
set(newValue){
console.log('set');
//在这个地方我们还需要实现视图的更新,也就是在这里实现compile这个方法,但是我们如何通过set之后触发呢,在这里我们使用观察者模式来实现
_this.dispatchEvent(new CustomEvent(key,{
detail:newValue
}))
value =newValue
}
})
})
}
compile(){
let ele = document.querySelector(this.$options.el);
let childNodes = ele.childNodes
childNodes.forEach(item=>{
if(item.nodeType === 1){
//元素节点
}else if(item.nodeType === 3){
//文本节点
// [^{}\s] :表示不能存在{}和空格
let reg = /\{\{\s*([^{}\s]+)\s*\}\}/g
let textContent = item.textContent;
if(reg.test(textContent)){
let $1 = RegExp.$1;
//正则匹配里面的replace方法
item.textContent = item.textContent.replace(reg,this._data[$1]);
//事件监听
this.addEventListener($1,(e)=>{
let oldValue = this._data[$1];
let newValue = e.detail;
item.textContent = item.textContent.replace(oldValue,newValue);
})
}
}
})
}
}
继续完善为多层级的方法:
//仅仅修改下面的方法,其他的地方没有变动:
compile(){
let ele = document.querySelector(this.$options.el);
this.compileNodes(ele);
}
compileNodes(ele){
let childNodes = ele.childNodes
childNodes.forEach(item=>{
if(item.nodeType === 1){
//元素节点
if(item.childNodes.length>0){
//通过递归的方式来处理多层数据,直到找到文本节点
this.compileNodes(item)
}
}else if(item.nodeType === 3){
//文本节点
// [^{}\s] :表示不能存在{}和空格
let reg = /\{\{\s*([^{}\s]+)\s*\}\}/g
let textContent = item.textContent;
if(reg.test(textContent)){
let $1 = RegExp.$1;
//正则匹配里面的replace方法
item.textContent = item.textContent.replace(reg,this._data[$1]);
//事件监听
this.addEventListener($1,(e)=>{
let oldValue = this._data[$1];
let newValue = e.detail;
item.textContent = item.textContent.replace(oldValue,newValue);
})
}
}
})
}
2.第二种实现方式:发布订阅模式
发布订阅模式广义上也是观察者模式;
发布订阅模式具体的实现过程:
//发布订阅模式
class Kvue {
constructor(options){
this.$options = options;
this._data = options.data;
this.observe(this._data);
this.compile();
}
observe(data){
let keys = Object.keys(data);
let _this = this;
keys.forEach(key=>{
let value = data[key];
let dep = new Dep();
Object.defineProperty(data,key,{
configurable:true,
emumerable:true,
get(){
console.log('get');
//收集watcher
if(Dep.target){
dep.addSub(Dep.target);
}
return value;
},
set(newValue){
console.log('set');
//在这个地方我们还需要实现视图的更新,也就是在这里实现类似compile这个方法,但是我们如何通过set之后触发呢,在这里我们使用观察者模式来实现
// _this.dispatchEvent(new CustomEvent(key,{
// detail:newValue
// }))
//执行watcher
dep.notify(newValue);
value = newValue
}
})
})
}
compile(){
let ele = document.querySelector(this.$options.el);
this.compileNodes(ele);
}
compileNodes(ele){
let childNodes = ele.childNodes
childNodes.forEach(item=>{
if(item.nodeType === 1){
//元素节点
if(item.childNodes.length>0){
//通过递归的方式来处理多层数据,直到找到文本节点
this.compileNodes(item)
}
}else if(item.nodeType === 3){
//文本节点
// [^{}\s] :表示不能存在{}和空格
let reg = /\{\{\s*([^{}\s]+)\s*\}\}/g
let textContent = item.textContent;
if(reg.test(textContent)){
let $1 = RegExp.$1;
//正则匹配里面的replace方法
item.textContent = item.textContent.replace(reg,this._data[$1]);
//事件监听
// this.addEventListener($1,(e)=>{
// let oldValue = this._data[$1];
// let newValue = e.detail;
// item.textContent = item.textContent.replace(oldValue,newValue);
// })
//初始化的时候我们就实例化watcher
new Watcher(this._data,$1,(newValue)=>{
let oldValue = this._data[$1];
item.textContent = item.textContent.replace(oldValue,newValue);
})
}
}
})
}
}
class Dep{
constructor(){
this.subs = [];
}
//手机watcher
addSub(sub){
this.subs.push(sub);
}
//通知watcher发生变化
notify(newValue){
this.subs.forEach(sub=>sub.update(newValue))
}
}
class Watcher{
constructor(data,key,cb){
//这个地方是很重要的一点,手机依赖的时候我们把new Watcher直接保存到Dep.target的静态属性中。
Dep.target = this;
//自动触发get方法,手机watcher
data[key];
this.cb = cb;
//把静态属性重置为null 防止数据累加
Dep.target = null;
}
update(newValue){
this.cb(newValue);
}
}
观察者模式:观察者与订阅者有之间的联系,发布订阅模式:观察者与订阅者之间没有之间联系,观察者模式属于紧解耦,发布订阅模式属于松解耦,发布订阅模式广义上属于观察者模式
3.vue3中通过proxy实现响应式:
关于下面代码中一个知识点:Reflect:为啥在这里使用Reflect呢?因为模块化中或者严格模式下,get和set中需要返回boolean的值,否则报错。
Reflect.set(target, propertyKey, value[, receiver]) 将值分配给属性的函数。返回一个Boolean,如果更新成功,则返回true。
Reflect.get(target, propertyKey[, receiver]) 获取对象身上某个属性的值,类似于 target[name]。
//proxy实现响应式:
class Kvue{
constructor(options){
this.$options = options;
this._data = options.data;
this.observe(this._data);
this.compile();
}
observe(data){
let temp = {};
this._data = new Proxy(data,{
get(target,key){
temp[key] = new Dep();
if(Dep.target){
temp[key].addSub(Dep.target);
}
return Reflect.get(target,key)
},
set(target,key,newValue){
temp[key].notify(newValue);
return Reflect.set(target,key,newValue)
}
})
}
compile(){
let ele = document.querySelector(this.$options.el);
this.compileNodes(ele);
}
compileNodes(ele){
let childNodes = ele.childNodes
childNodes.forEach(item=>{
if(item.nodeType === 1){
//元素节点
if(item.childNodes.length>0){
//通过递归的方式来处理多层数据,直到找到文本节点
this.compileNodes(item)
}
}else if(item.nodeType === 3){
//文本节点
// [^{}\s] :表示不能存在{}和空格
let reg = /\{\{\s*([^{}\s]+)\s*\}\}/g
let textContent = item.textContent;
if(reg.test(textContent)){
let $1 = RegExp.$1;
//正则匹配里面的replace方法
item.textContent = item.textContent.replace(reg,this._data[$1]);
//事件监听
// this.addEventListener($1,(e)=>{
// let oldValue = this._data[$1];
// let newValue = e.detail;
// item.textContent = item.textContent.replace(oldValue,newValue);
// })
//初始化的时候我们就实例化watcher
new Watcher(this._data,$1,(newValue)=>{
let oldValue = this._data[$1];
item.textContent = item.textContent.replace(oldValue,newValue);
})
}
}
})
}
}
class Dep{
constructor(){
this.subs = [];
}
addSub(sub){
this.subs.push(sub);
}
notify(newValue){
this.subs.forEach(sub=>sub.update(newValue));
}
}
class Watcher{
constructor(data,key,cb){
Dep.target = this;
data[key];
this.cb = cb;
Dep.target = null;
}
update(newValue){
this.cb(newValue);
}
}
4.通过input的v-model来实现双向绑定:
//代码如下:
class Kvue{
constructor(options){
this.$options = options;
this._data = options.data;
this.observe(this._data);
this.compile();
}
observe(data){
let temp = {};
this._data = new Proxy(data,{
get(target,key){
console.log('get');
temp[key] = new Dep();
if(Dep.target){
temp[key].addSub(Dep.target);
}
return Reflect.get(target,key)
},
set(target,key,newValue){
console.log('set');
temp[key].notify(newValue);
return Reflect.set(target,key,newValue)
}
})
}
compile(){
let ele = document.querySelector(this.$options.el);
this.compileNodes(ele);
}
compileNodes(ele){
let childNodes = ele.childNodes
childNodes.forEach(item=>{
if(item.nodeType === 1){
//元素节点
let attrs = item.attributes;
[...attrs].forEach(attr=>{
let attrName = attr.name;
let attrValue = attr.value;
if(attrName === 'v-model'){
console.log(attrName,attrValue)
item.value = this._data[attrValue];
item.addEventListener('input',(e)=>{
console.log(e.target.value);
let newValue = e.target.value;
this._data[attrValue] = newValue;
})
}
})
if(item.childNodes.length>0){
//通过递归的方式来处理多层数据,直到找到文本节点
this.compileNodes(item)
}
}else if(item.nodeType === 3){
//文本节点
// [^{}\s] :表示不能存在{}和空格
let reg = /\{\{\s*([^{}\s]+)\s*\}\}/g
let textContent = item.textContent;
if(reg.test(textContent)){
let $1 = RegExp.$1;
//正则匹配里面的replace方法
item.textContent = item.textContent.replace(reg,this._data[$1]);
//事件监听
// this.addEventListener($1,(e)=>{
// let oldValue = this._data[$1];
// let newValue = e.detail;
// item.textContent = item.textContent.replace(oldValue,newValue);
// })
//初始化的时候我们就实例化watcher
new Watcher(this._data,$1,(newValue)=>{
let oldValue = this._data[$1];
item.textContent = item.textContent.replace(oldValue,newValue);
})
}
}
})
}
}
class Dep{
constructor(){
this.subs = [];
}
addSub(sub){
this.subs.push(sub);
}
notify(newValue){
this.subs.forEach(sub=>sub.update(newValue));
}
}
class Watcher{
constructor(data,key,cb){
Dep.target = this;
data[key];
this.cb = cb;
// Dep.target = null;
}
update(newValue){
this.cb(newValue);
}
}
5.实现v-html 和v-text
class Kvue{
constructor(options){
this.$options = options;
this._data = options.data;
this.observe(this._data);
this.compile();
}
observe(data){
let temp = {};
this._data = new Proxy(data,{
get(target,key){
console.log('get');
temp[key] = new Dep();
if(Dep.target){
temp[key].addSub(Dep.target);
}
return Reflect.get(target,key)
},
set(target,key,newValue){
console.log('set');
temp[key].notify(newValue);
return Reflect.set(target,key,newValue)
}
})
}
compile(){
let ele = document.querySelector(this.$options.el);
this.compileNodes(ele);
}
compileNodes(ele){
let childNodes = ele.childNodes
childNodes.forEach(item=>{
if(item.nodeType === 1){
//元素节点
let attrs = item.attributes;
[...attrs].forEach(attr=>{
let attrName = attr.name;
let attrValue = attr.value;
if(attrName === 'v-model'){
console.log(attrName,attrValue)
item.value = this._data[attrValue];
item.addEventListener('input',(e)=>{
console.log(e.target.value);
let newValue = e.target.value;
this._data[attrValue] = newValue;
})
}else if(attrName === 'v-html'){
item.innerHTML = this._data[attrValue];
//收集watcher
new Watcher(this._data,attrValue,newValue=>{
item.innerHTML = newValue;
})
}else if(attrName === 'v-text'){
item.innerText = this._data[attrValue];
new Watcher(this._data,attrValue,newValue=>{
item.innerText = newValue;
})
}
})
if(item.childNodes.length>0){
//通过递归的方式来处理多层数据,直到找到文本节点
this.compileNodes(item)
}
}else if(item.nodeType === 3){
//文本节点
// [^{}\s] :表示不能存在{}和空格
let reg = /\{\{\s*([^{}\s]+)\s*\}\}/g
let textContent = item.textContent;
if(reg.test(textContent)){
let $1 = RegExp.$1;
//正则匹配里面的replace方法
item.textContent = item.textContent.replace(reg,this._data[$1]);
//事件监听
// this.addEventListener($1,(e)=>{
// let oldValue = this._data[$1];
// let newValue = e.detail;
// item.textContent = item.textContent.replace(oldValue,newValue);
// })
//初始化的时候我们就实例化watcher
new Watcher(this._data,$1,(newValue)=>{
let oldValue = this._data[$1];
item.textContent = item.textContent.replace(oldValue,newValue);
})
}
}
})
}
}
class Dep{
constructor(){
this.subs = [];
}
addSub(sub){
this.subs.push(sub);
}
notify(newValue){
this.subs.forEach(sub=>sub.update(newValue));
}
}
class Watcher{
constructor(data,key,cb){
Dep.target = this;
data[key];
this.cb = cb;
// Dep.target = null;
}
update(newValue){
this.cb(newValue);
}
}
六、call、apply、bind的手动实现
直接看代码:
1.call实现:
Function.prototype.mycall = functionn(context){
//先判断mycall是不是一个函数,这里的this就是调用的mycall
if(typeof this!== 'function'){
throw new TypeError('Not a Function');
}
//不传参数表示的是window
context = context || window;
//保存this
context.fn = this;
//处理参数
let args = array.from(arguments).slice(1);
//执行
let result = context.fn(...args);
//删除
delete context.fn;
//
return rusult;
}
2.apply实现:
Function.prototype.myApply = function(context){
if(typeof context!=='function'){
throw new TypeError('Not a Function');
}
context = context || window;
let result;
//保存this
context.fn = this;
//处理参数
let args = Array.from(arguments).slice(1);
//判断是否有参数
if(arguments[1]){
//这个时候arguments是个数组
result = context.fn(...arguments[1])
}else{
result = context.fn();
}
delete context.fn;
return result;
}
3.bind的实现
Function.prototype.myBind = function(context){
// 判断是否是一个函数
if(typeof this !== "function") {
throw new TypeError("Not a Function")
}
// 保存调用bind的函数
const _this = this
// 保存参数
const args = Array.prototype.slice.call(arguments,1)
// 返回一个函数
return function F () {
// 判断是不是new出来的
if(this instanceof F) {
// 如果是new出来的
// 返回一个空对象,且使创建出来的实例的__proto__指向_this的prototype,且完成函数柯里化
return new _this(...args,...arguments)
}else{
// 如果不是new出来的改变this指向,且完成函数柯里化
return _this.apply(context,args.concat(...arguments))
}
}
}
七、手动实现一个new
// 手写一个new
function myNew(fn, ...args) {
// 创建一个空对象
let obj = {}
// 使空对象的隐式原型指向原函数的显式原型
obj.__proto__ = fn.prototype
// this指向obj
let result = fn.apply(obj, args)
// 返回
return result instanceof Object ? result : obj
}
function Person(name){
this.name = name;
}
let p2 = myNew(Person,'李四');
console.log(p2);