What is happening in Crockford's object creation technique?

后端 未结 4 956
长发绾君心
长发绾君心 2020-12-13 01:40

There are only 3 lines of code, and yet I\'m having trouble fully grasping this:

Object.create = function (o) {
    function F() {}
    F.prototype = o;
             


        
4条回答
  •  再見小時候
    2020-12-13 02:02

    > Clearly it won't be possible to have a constructor function using this technique.

    The technique is already an object constructor since it returns new F(), but no property values can be set as for say new man('John','Smith'). However, if the Object.create code is modified, instantiation is possible. For example the sarah object below can be constructed and instantiated using Object.creator, and will inherit the getName method.

    var girl = {
       name: '',
       traits: {},
       getName: function(){return this.name}
    }
    
    var sarah = Object.creator(girl, 'Sarah', {age:29,weight:90})
    

    The sarah object will then consist of own properties { name:'Sarah', traits:{age:9,weight:49} }, and the prototype inherited sarah.getName() will produce 'Sarah'.

    The following method relies on own properties enumerating with 'for(prop in o)' in creation order. Although not guaranteed by ECMA specs, this example (and a few more complex) worked for all major browsers (4) tested, providied hasOwnProperty() was used, otherwise not.

    Object.creator = function(o) {
       var makeArgs = arguments 
       function F() {
          var prop, i=1, arg, val
          for(prop in o) {
             if(!o.hasOwnProperty(prop)) continue
             val = o[prop]
             arg = makeArgs[i++]
             if(typeof arg === 'undefined') break
             this[prop] = arg
          }
       }
       F.prototype = o
       return new F()
    }
    

    The official ECMA Object.create has an optional 2nd parameter, propertiesObject, that can instantiate property values, but it is an object rather than the usual list, and looks awkward to use. E.g. I believe:-

    o2 = Object.create({}, { p: { value: 42, writable: true, enumerable: true, configurable: true } });
    

    is equivalent to the much simpler old way:-

    o2 = new function(p) { this.p=p }(42)
    

    and

    o2 = Object.creator({p:''}, 42)
    

提交回复
热议问题