唠唠那些坑

1. 观察订阅模式

class Test {
  constructor() {
    this.events = {};
  }

  on(eName, cb) {
    if (this.events[eName]) {
      this.events[eName].push(cb);
    } else {
      this.events[eName] = [cb];
    }
  }

  trigger(eName) {
    if (!this.events[eName]) {
      console.log(`no such event to trigger: ${eName}`);
      return;
    }
    this.events[eName].forEach((subFn) => {
      subFn();
    });
  }

  off(eName, cb) {
    if (!this.events[eName]) {
      console.log(`no such event to off: ${eName}`);
      return;
    }
    const matchIndex = this.events[eName].findIndex((fn) => fn === cb);
    if (matchIndex !== -1) {
      this.events[eName].splice(matchIndex, 1);
    } else {
      console.log('no match cb');
    }
  }

  once(eName, cb) {
    const temFn = () => {
      cb();
      this.off(eName, temFn);
    };
    this.on(eName, temFn);
  }
}

const testObj = new Test();

const test1Cb = () => { console.log('it is test11'); };
const test1OnceCb = () => { console.log('it is once test11'); };
testObj.on('test1', test1Cb);
testObj.once('test1', test1OnceCb);
// testObj.off('test1', test1Cb);
testObj.trigger('test1');
testObj.trigger('test1');
testObj.trigger('test1');
testObj.trigger('test12');

2.box-size

content-box | border-box

3. js 中 script 标签引入内容的执行顺序

4. 动态获取窗口的宽高

5. 链表的交集

以Y形交集为例: 取m,n最小值遍历

6. tcp和udp的区别及其使用场景

7. react class 和 hook的区别, 为什么引入hook?

  1. hook中将不再使用this
  2. hook简化了逻辑复用
  3. 在 Class 组件中,代码是从技术角度组织在一起的,例如在 componentDidMount 中都去做一些初始化的事情。而在函数组件中,代码是从业务角度组织在一起的,相关代码能够出现在集中的地方,从而更容易理解和维护。

8. react如何实现的hook?

https://blog.csdn.net/sd19871122/article/details/105935346/
https://blog.51cto.com/feng/5289564
https://juejin.cn/post/7021058967728029704

import React from 'react';
import ReactDOM from 'react-dom';

const memorizedState = [];
let key = 0;

function useState(state) {
  memorizedState[key] = memorizedState[key] || state;
  const currentK = key;
  function setState(newState) {
    memorizedState[currentK] = newState;
    render();
  }
  // key += 1;
  return [memorizedState[key++], setState];
}

function useEffect(fn, dependencies) {
  if (!dependencies) {
    key++;
    return fn();
  }
  const currentDep = memorizedState[key];
  const shouldRun = currentDep ? !dependencies.every((i, k) => i === currentDep[k]) : true;
  if (shouldRun) {
    fn();
    memorizedState[key] = dependencies;
  }
  key++;
}

function Counter() {
  const [name, setName] = useState('counter');
  const [num, setNum] = useState(0);

  useEffect(() => {
    console.log('111111');
  }, [name, num]);
  return (
    <>
      

{name}: {num}

); } function render() { key = 0; ReactDOM.render(, document.querySelector('body')); } render();

你可能感兴趣的:(唠唠那些坑)