Using "Object.create" instead of "new"

Posted by Graham King on Stack Overflow See other posts from Stack Overflow or by Graham King
Published on 2010-04-25T19:36:08Z Indexed on 2010/04/25 20:23 UTC
Read the original article Hit count: 367

Filed under:
|
|
|

Javascript 1.9.3 / ECMAScript 5 introduces Object.create, which Douglas Crockford amongst others has been advocating for a long time. How do I replace new in the code below with Object.create?

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();

(Assume MY_GLOBAL.nextId exists).

The best I can come up with is:

var userB = {
    init: function(nameParam) {
        this.id = MY_GLOBAL.nextId();
        this.name = nameParam;
    },
    sayHello: function() {
        console.log('Hello '+ this.name);
    }
};
var bob = Object.create(userB);
bob.init('Bob');
bob.sayHello();

There doesn't seem to be any advantage, so I think I'm not getting it. I'm probably being too neo-classical. How should I use Object.create to create user 'bob'?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about create