如何写好js
- 各司其职
- 复杂UI组件设计
1.结构设计 2.api设计 3.控制流设计 - 优化 1:插件/依赖注入 2:改进插件\模块化 3:组件模型抽象
- 局部细节控制
高阶函数
once、throttle、debounced、consumer、iterative
它们自身输入函数或返回函数,被称为高阶函数
function once(fn){
return function(...args){
if(fn){
let ret = fn.apply(this, args);
fn = null;
return ret;
}
}
}
function throttle(fn, time = 500){
let timer;
return function(...args){
if(timer == null){
fn.apply(this, args);
timer = setTimeout(() => {
timer = null;
}, time)
}
}
}
function debounce(fn){
let timer = null
return function(...args){
if(timer != null) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
timer = null
}, 300)
}
function consumer(fn, time){
let tasks = [],
timer;
return function(...args){
tasks.push(fn.bind(this, ...args));
if(timer == null){
timer = setInterval(() => {
tasks.shift().call(this)
if(tasks.length <= 0){
clearInterval(timer);
timer = null;
}
}, time)
}
}
}
function iterative(fn){
return function(...args){
return args.reduce(fn.bind(this));
}
}
function toggle(...actions){
return function(...args){
let action = actions.shift();
actions.push(action);
return action.apply(this, args);
}
}
Declarativev.s. Imperative
How to do?
let list = [1, 2, 3, 4];
let map1 = [];
for(let i = 0; i < list.length; i++){
map1.push(list[i] * 2);
}
What to do?
let list = [1, 2, 3, 4];
const double = x => x * 2;
list.map(double);
总结如何写好 JavaScript?
- 各司其职:JavaScript 尽量只做状态管理
- 结构、API、控制流分离设计 UI 组件
- 插件和模板化,并抽象出组件模型
- 运用过程抽象的技巧来抽象并优化局部 API