NOW, today, let us extend to implement a function.
Specific ideas: the use Object.defineProperty () characteristics attribute set, and () acquired by the attribute descriptor Object.getOwnPropertyDescriptor, and assigned to the newly created object
Let's pull the code out yo
Object.defineProperty (Object.prototype, "Extend" , { Writable: to true , Enumerable: to false , Configurable: to true , value: function (O) { // Get all properties owned var names = Object.getOwnPropertyNames (O); for ( var I = 0; I <of names.length; I ++ ) { // if the attribute exists skip IF (names [I] in the this ) Continue ; // get attributes of the attribute descriptor SS var desc = Object.getOwnPropertyDescriptor (O, names [I]); Object.defineProperty ( the this , names [I], desc) } } } )
Example of use:
// define a new object var A = { itemA: . 1 } // create a new attribute, and set the attribute descriptor Object.defineProperty (A, "itemB" , { Writable: to true , Enumerable: to false , Configurable: to true , value: 2 }) // then define a new object var B = {} b.extend (a) // At this point we can see the static properties have inherited passed the console.log (B) // results {itemA: 1, itemB: 2} // look at the property descriptor is not also passed let extendDesc = Object.getOwnPropertyDescriptor(b,"itemB") console.log(extendDesc) // 结果为{value: 2, writable: true, enumerable: false, configurable: true}
Well, the end, we have the opportunity to work together to achieve what analog Object.create () function