JavaScript

类型

  • 声明对象
    • object:
      1
      2
      let person = new Object()
      let person = {}
    • Array:
      1
      2
      let arr = new Array()
      let arr = {}

检测类型

  • 基础数据类型

    • undefined,null,boolean,number,string,symbol
  • 引用数据类型

    • object
  • typeof

    • “undefined”
    • “boolean”
    • “string”
    • “number”
    • “object” 对象或者 null
    • “function”
  • 引用类型

    • instanceof
  • 检测数组

    • Array.isArray()
  • 检测类型

    1
    2
    Object.prototype.toString.call()


实现重载

1
2
3
4
5
6
7
8
9
10
function addMethod(obj,name,func){
var old = obj[name];
obj[name] = function(){
if(arguments.length === func.length){
return func.apply(this,arguments);
}else if(typeof old === "function"){
return old.apply(this,arguments);
}
}
}

数组操作

  • push() 推入数组末尾
  • pop() 从数组末尾取出
  • unshift() 数组前端添加
  • shift() 数组前端取出

栈操作

  • push() 推入 pop()取出

队列操作

  • push() 推入 shift()取出

操作数组

  • slice(a,b) 返回 a-b 之间的值,含 a 不含 b
  • splice(a,b,…) 删除 a 开始,b 个值,包含 a. 再插入…

EventLoop

event loop 主要为三个部分,主线程,宏队列,微队列。

宏队列:settimeout/setImmediate、I/O、UI rendering。

微队列:promise.then、process.nextTick

执行顺序

  1. 先执行主线程

  2. 遇到宏队列(macrotask)放到宏队列(macrotask)

  3. 遇到微队列(microtask)放到微队列(microtask)

  4. 主线程执行完毕

  5. 执行微队列(microtask),微队列(microtask)执行完毕

  6. 执行一次宏队列(macrotask)中的一个任务,执行完毕

  7. 执行微队列(microtask),执行完毕

  8. 依次循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
console.log(1)
process.nextTick(() => {
console.log(8)
setTimeout(() => {
console.log(9)
})
})
setTimeout(() => {
console.log(2)
new Promise(() => {
console.log(11)
})
})
requestIdleCallback(() => {
console.log(7)
})// 特殊说明: new Promise()属于主线程任务
let promise = new Promise((resolve,reject) => {
setTimeout(() => {
console.log(10)
})
resolve() // 这个console也属于主线程任务
console.log(4)
})
fn()
console.log(3)
promise.then(() => {
console.log(12)
})
function fn(){
console.log(6)
}

log: 1 4 6 3 12 8 2 11 10 9 7

call() bind() apply()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
let C = {
bName: "bName",
func: function (a, b, c) {
console.log("func", this.bName, a, b, c);
},
func1: () => {
console.log("func1", this.bName);
},
};

this.bName = "gName";

C.func(1, 2);
C.func1();
C.func.call(this, 1, 2, 3);

let f = C.func.bind(C, 1);
let f1 = C.func;
let f2 = C.func1;

f(4);
f1(1, 2, 3);
f2();