soulJF999 / dailyRecord

1 stars 0 forks source link

迁移五 #47

Open soulJF999 opened 3 years ago

soulJF999 commented 3 years ago

简略mvvm var obj = {} // 为obj定义一个名为hello的访问器属性 Object.definePrototype(obj, 'hello', { get: function() {return sth} set: function(val) {/ do sth /} }) obj.hello // 可以像普通属性一样读取访问器属性 访问器属性的“值”比较特殊,读取或设置访问器属性的值,实际上是调用其内部特性:get和set函数 obj.hello // 读取属性,就是调用get函数并返回get函数的返回值 obj.hello = 'abc' // 为属性赋值,就是调用set函数,赋值其实是传参

get和set方法内部的this都指向obj,这意味着get和set函数可以操作对象内部的值。另外,访问器属性会“覆盖”同名的普通属性,因为访问器属性会被优先访问,与其同名的普通属性则会被忽略

极简双向绑定的实现

DocumentFragment DocumentFragment可以看作节点容器,它可以包含多个子节点,当我们将它插入到DOM中时,只有它的子节点会插入目标节点,所以把它看作一组节点的容器。使用DocumentFragment处理节点,速度和性能优于直接操作dom

promise ` function Promise(fn) { this.cbs = [] const resolve = (value) => { setTimeout(() => { this.data = value this.cbs.forEach((cb) => cb(value)) }) } fn(resolve) }

Promise.prototype.then = function(onResolved) { return new Promise((resolve) => { this.cbs.push(() => { const res = onResolved(this.data) if(res instanceof Promise){ res.then(resolve) } else { resolve(res) } }) }) } `

koa ` class Koa { constructor () { this.middlewares = [] } use(middleware) { this.middlewares.push(middleware) } start({req}) { const composed = composeMiddlewares(this.middlewares) const ctx = {req, res:undefined} return composed(ctx) } }

function composeMiddlewares(middlewares) { return function wrapmiddlewares(ctx) { let index = 1 function dispatch(i) { index = i const fn = middlewares[i]

if(!fn) { return Promise.resolve() }

return Promise.resolve(fn(ctx, () => dispatch(i + 1))) } return dispatch(0) } } `