在看koa源码的时候, 发现使用了

createContext(req, res){
        const ctx = Object.create(context)
        console.log(ctx);
        ctx.request = Object.create(request)
        ctx.response = Object.create(response)
        ctx.req = ctx.request.req = req;
        ctx.res = ctx.response.res = res;
        return ctx;
 }
用来构建上下文对象
Object。create主要是在继承时使用。
为什么用Object.create而不是直接传呢?
因为想似的对象纯传自己的属性, 而不要原型链上的
 
Object.create(source, [restprops, restprops.....])
当 var a = {'MM':1}
命令行将打印出来许多其他的_proto_, 也就是原型继承来很多tostring, hasownproties等属性或方法
可是如果这样复制
var a = Object.create(null, {MM: {congiuration:true, value: '1'}})
那么, 打印出来的仅仅是 var a = {'MM': 1}
 
那是如果, Object.create({}, {confiurgation:true, value: '1'}) ,将返回两层_proto__
 
如果, Object.create(Object.protototype, {confiurgation:true, value: '1'}),将和var a = {'MM':1}一样
 
 
还有如何判断toString是原型链上的还是自有属性呢。 有个方法叫hasOwnProtoies
 
正确的做法是 Object.hasOwnPrototype.call(a, 'toString')
为什么不能直接用a.hasOwnProperty('toString')?因为你可能给a添加了一个自定义的hasOwnProperty
这样是不对的, 这样会去到原型寻找。 a.toString //functon
但是
var a = object.create(null)
a.toString //undeifned
 
 
posted on 2021-05-19 07:52  connie313  阅读(262)  评论(0编辑  收藏  举报