Vue3

slot APi的变化

全局API使用规范

teleport

Composition API

v-model变化

指令API的变化

算法

image.png
image.png

手撕

call

  1. // call用于改变this指向,第一个参数要指向的对象,剩余参数是传入的参数
  2. Function.prototype.myCall(context){
  3. // 调用者校验
  4. if(typeof this !== 'function'){
  5. throw new Error('not a function');
  6. }
  7. // 参数校验,为null的话执行window
  8. context = context || window;
  9. // 参数处理
  10. let args = [...arguments].slice(1);
  11. let result = null;
  12. // 设置对象的临时属性 指向this
  13. context.fn = this;
  14. // 存储
  15. result = context.fn(args);
  16. // 删除
  17. delete context.fn;
  18. return result;
  19. }

apply

  1. Function.prototype.myApply(context){
  2. if(typeof this !== 'function'){
  3. throw new Error('Not A Function');
  4. }
  5. context = context || window;
  6. let args = arguments[1];
  7. let result = null;
  8. context.fn = this;
  9. result = context.fn(args);
  10. delete context.fn;
  11. return result;
  12. }

bind

  1. Function.prototype.myBind(context){
  2. if(typeof this !== 'function'){
  3. throw new Error('Not A Function');
  4. }
  5. // bind方法会返回一个新函数
  6. let fn = this;
  7. // 参数处理
  8. let args = [...arguments].slice(1);
  9. let TempFn = function(){};
  10. let resFn = function(){
  11. let newArgs = [...arguments]
  12. // 根据调用方式不同,传入不同this
  13. return fn.apply(
  14. // 当返回出去的函数作为普通函数调用时,this指向window
  15. // 当返回出去的函数作为构造函数调用时,this指向实例,resFn其原型链上
  16. this instanceof resFn ? this : context, args.concat(newArgs);
  17. )
  18. }
  19. // 继承实现
  20. TempFn.prototype = this.prototype;
  21. resFn.prototype = new TempFn();
  22. return resFn;
  23. }

new

  1. // 调用new的过程中会发生以下四件事
  2. // 1. 创建一个空对象
  3. // 2. 将对象的原型设置为函数的prototype对象
  4. // 3. 改变函数的this指向,让构造函数的this指向该对象,然后执行构造函数代码
  5. // 4. 判断构造函数的返回类型
  6. // 4.1 如果是值类型,那么返回刚刚创建的对象
  7. // 4.2 如果是引用类型,就返回这个引用
  8. // 使用方法,第一个参数为构造函数,剩余的为其他参数
  9. function objectFactory(){
  10. // 拿到构造函数然后做一个校验
  11. let constructor = Array.prototype.shift.call(arguments);
  12. if(typeof constructor !== 'function'){
  13. throw new Error('Not A Function');
  14. }
  15. // 1 2
  16. let newObject = Object.create(constructor.prototype);
  17. // 3
  18. let result = constructor.apply(newObject, arguments);
  19. // 4
  20. let flag = result && (typeof result === 'object' || typeof result === 'function');
  21. return flag ? result : newObject;
  22. }

Curry

  1. // 把传入的参数保存在闭包中,等到参数数量足够函数执行了,再执行函数
  2. function createCurry(func){
  3. let len = func.length;
  4. function resFunction(...args){
  5. if(args.length >= len){
  6. return func.apply(this, args);
  7. }else{
  8. function tempCurry(...newArgs){
  9. return resFunction.apply(this, [...args, ...newArgs]);
  10. }
  11. return tempCurry;
  12. }
  13. }
  14. return resFunction;
  15. }