Creating JS object with Object.create(null)?

前端 未结 5 511
不知归路
不知归路 2020-11-28 01:58

I know a lot of ways to create JS objects but I didn\'t know the Object.create(null)\'s one.

Question:

is it exactly the same as:

5条回答
  •  囚心锁ツ
    2020-11-28 02:42

    If someone is looking for implementing Object.create(null), just to know how it works. It is written using __proto__ which is non-standard and hence, I do not recommend it.

    function objectCreateMimic()
    {
      /*optional parameters: prototype_object, own_properties*/
      var P = arguments.length>0?arguments[0]:-1;
      var Q = arguments.length>1?arguments[1]:null;
      var o = {};
      if(P!==null && typeof P === "object")
      {
        o.__proto__ = P;
      }
      else if(P===null)
      {
        o.__proto__ = null;
      }
      if(Q!==null && typeof Q === "object")
      {
       for(var key in Q)
       {
         o[key] = Q[key];
       }
      }
      return o;
    }
    

    Note: I wrote this, out of curiosity, and it is only written in simple terms, for instance, I am not transferring the property descriptors from the second object to the return object.

提交回复
热议问题