zoukankan      html  css  js  c++  java
  • object.create的用途

    在看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
     
     
  • 相关阅读:
    cpp:博文_注意
    Algs4-1.2(非习题)String
    Algs4-1.2(非习题)几何对象中的一个2D用例
    Algs4-1.2.19字符串解析
    Algs4-1.2.18累加器的方差
    Algs4-1.2.17有理数实现的健壮性
    Algs4-1.2.16有理数
    Algs4-1.2.15基于String的split()的方法实现In中的静态方法readInts()
    Algs4-1.2.13实现Transaction类型
    Algs4-1.2.14实现Transaction中的equals()方法
  • 原文地址:https://www.cnblogs.com/connie313/p/14783552.html
Copyright © 2011-2022 走看看