Page 175 - 你不知道的JavaScript(上卷)
P. 175

Object.create()的polyfill代码
               Object.create(..) 是在 ES5 中新增的函数,所以在 ES5 之前的环境中(比如旧 IE)如
               果要支持这个功能的话就需要使用一段简单的 polyfill 代码,它部分实现了 Object.
               create(..) 的功能:

                   if (!Object.create) {
                       Object.create = function(o) {
                           function F(){}
                           F.prototype = o;
                           return new F();
                       };
                   }
               这段 polyfill 代码使用了一个一次性函数 F,我们通过改写它的 .prototype 属性使其指向想
               要关联的对象,然后再使用 new F() 来构造一个新对象进行关联。

               由于 Object.create(..c) 可以被模拟,因此这个函数被应用得非常广泛。标准 ES5 中内
               置的 Object.create(..) 函数还提供了一系列附加功能,但是 ES5 之前的版本不支持这些
               功能。通常来说,这些功能的应用范围要小得多,但是出于完整性考虑,我们还是介绍一
               下:
                   var anotherObject = {
                       a:2
                   };

                   var myObject = Object.create( anotherObject, {
                       b: {
                           enumerable: false,
                           writable: true,
                           configurable: false,
                           value: 3
                       },
                       c: {
                           enumerable: true,
                           writable: false,
                           configurable: false,
                           value: 4
                       }
                   });

                   myObject.hasOwnProperty( "a" ); // false
                   myObject.hasOwnProperty( "b" ); // true
                   myObject.hasOwnProperty( "c" ); // true

                   myObject.a; // 2
                   myObject.b; // 3
                   myObject.c; // 4
               Object.create(..) 的第二个参数指定了需要添加到新对象中的属性名以及这些属性的属性




               160   |   第 5 章
   170   171   172   173   174   175   176   177   178   179   180