Home > Web Front-end > JS Tutorial > body text

Object.create: A Better Way to Instantiate Objects Than `new`?

Linda Hamilton
Release: 2024-11-16 20:02:03
Original
900 people have browsed it

Object.create: A Better Way to Instantiate Objects Than `new`?

Object.create: A New Way to Instantiate Objects

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();
Copy after login

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
    }
});
Copy after login

Advantages of Object.create

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template