Javascript 1.9.3 / ECMAScript 5 introduced Object.create, a method that has been highly advocated by Douglas Crockford and others. This method provides an alternative to the traditional new keyword when instantiating objects.
To replace new with Object.create, let's examine the following code:
var UserA = function(nameParam) { this.id = MY_GLOBAL.nextId(); this.name = nameParam; } UserA.prototype.sayHello = function() { console.log('Hello '+ this.name); } var bob = new UserA('bob'); bob.sayHello();
Assuming MY_GLOBAL.nextId exists, we can instantiate UserA using Object.create as follows:
var userB = { sayHello: function() { console.log('Hello '+ this.name); } }; var bob = Object.create(userB, { 'id' : { value: MY_GLOBAL.nextId(), enumerable: true }, 'name': { value: 'Bob', enumerable: true } });
One advantage of Object.create over new is that it allows for differential inheritance. Objects can directly inherit properties from other objects without the need for a prototype chain. This is done by passing an object as the second argument to Object.create, where you can define the inherited properties.
Another advantage is its flexibility. Object.create allows you to set property attributes (enumerable, writable, configurable) using the property descriptors syntax, giving you greater control over the behavior of object properties.
The above is the detailed content of Object.create: A Better Way to Instantiate Objects Than `new`?. For more information, please follow other related articles on the PHP Chinese website!