关于Typescript-接口(interface)的总结

一. 接口(interface)是什么

接口就是用代码描述对象必须有什么属性(包括方法),可以理解为”要求”;

是用来描述对象

举例:

例一:

1
2
3
4
5
6

interface Human{
name : string,
age : number
}
let lisle:Human = {name:'lisle',age : 20}

例二

1
2
3
4
5
6
7
8
9
10
interface Human{
name : string;
age : number;
say(word:string):void;
shape: Shape;
}
interface Shape{
body:string;
head : string;
}

二. 接口(interface)的特性

interface描述只读属性
1
2
3
4
interface Human{
readonly sex : string;
name : string
}
interface描述可选属性
1
2
3
4
5
interface Human{
readonly sex : string;
name : string;
play?: string
}

阅读全文

几句话讲清楚节流和防抖

一. 节流和防抖的含义

throttle 和 debounce 是解决请求和响应速度不匹配问题的两个方案。二者的差异在于选择不同的策略。

假设间隔都是15s;

throttle : 节流,即强制减少触发次数,规定特定时间内只能执行一次;

第一次请求进来马上执行。从第二次请求开始,如果下一次与上一次执行的间隔不到15s,则不执行;否则就执行。

假设频繁触发的话,最终表现为两次请求间隔就是15s左右;

如果间隔不够,抛弃的是后面的请求。保证每 X 毫秒恒定的执行次数,比如每200ms检查下滚动位置,并触发 CSS 动画。

debounce : 防抖,即停止触发后才执行

每次请求进来,都要等待15s,确定15s后没有新请求进来再执行。

假设频繁触发的话,最终表现为两次请求间隔是无限长

二. 使用场景

throttle : 页面滚动检测距离底部距离,然后加载数据

只需要保证特定时间内只触发一次就行了

debounce : input搜索框输入 调整页面大小resize

重点: 我们只关心最后一次的输入

三. 简单实现

debounce :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

function debounce(func, wait) {
var timeout;

return function () {
var context = this;
var args = arguments;

clearTimeout(timeout)
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
}

var count = 1;
var container = document.getElementById('container');

function getUserAction() {
container.innerHTML = count++;
};
container.onmousemove = debounce(getUserAction, 1000);

阅读全文

几句话讲清楚javascript原型

一. 关于原型

记住以下几点:

  1. 所有的引用类型(数组,对象,函数)都有一个__proto__(隐式原型)属性,属性值是一个普通的对象。

  2. 所有的函数都有一个prototype(显式原型)属性,属性值也是一个普通对象

  3. 所有的引用类型(数组,对象,函数),他的proto属性指向它的构造函数的prototype属性

  4. 基础类型没有proto属性(也没有instanceof之类的,但是new出来的有)

1
2
3
4
const obj = new Object()


obj.__proto__ === Object.prototype //true
1
2
3
4
5
6
7
8
let a = 1;
a instanceof Number //false
let b = new Number(1)
b instanceof Number //true
typeof a //number
typeof b //object
a == b //true
a === b //false

当试图得到一个对象的某个属性的时候,如果这个对象本身没有这个属性,那么会去它的proto(即它的prototype)中去寻找

阅读全文