wootscootinboogie
wootscootinboogie

Reputation: 8695

Setting properties of JavaScript objects created with Object.create()

Let's say there's a simple object created with the following JavaScript

 Builder = function (firstName, lastName) {
                this.firstName = firstName;
                this.lastName = lastName;
            }
            Builder.prototype.build = function () {
                return 'building....';
            };
            var b2 = new Builder('firstName', 'lastName');

I've been reading up on some of Douglas Crockford's work and he says that it's 'better' to create objects like the following:

 var builder = {
                build: function () {
                    return 'building...';

                }, firstName: 'firstName'
                , lastName: 'lastName'
            };
            var b1 = Object.create(builder);

The Object.create() way is 'better' (and I would be curious to hear from an expert as to why), but I don't see how we could easily pass parameters to the second version for the values of 'firstNameand 'lastName. I'm much more familiar with C family syntax languages than JavaScript, but it seems to me that the constructor method of object creation is 'better'. Why am I wrong? (Let's say for an enterprise-level environment)

Upvotes: 0

Views: 62

Answers (2)

go-oleg
go-oleg

Reputation: 19480

You can pass initial values for firstName and lastName in the second argument to Object.create():

var builder = {
    getFullName : function() {
        return this.firstName + " " + this.lastName;
    }
};

var b1 = Object.create(builder, {
    firstName : { writable:true, configurable:true, value: "Joe" },
    lastName : { writable:true, configurable:true, value: "Shmoe" }
  }
);

b1.getFullName() //prints out: Joe Shmoe

Its very verbose, but you can create your own wrapper.

More details/examples here.

Upvotes: 1

ilan berci
ilan berci

Reputation: 3881

For Crockford's way, you would do the following:

  var build = function(firstName, lastName) {
    // do private stuff here.. but this closure will still be accessible to the returned object
    return {
      firstName:firstName,
      lastName:lastName
    }
  }

var b = build('john', 'smith')

It's just as clean/powerfull as the OO way

Crockford's argument was that OO doesn't mix well with protypical inheritance. He felt as though many of the OO constructs were added to the language and should have been thought out more clearly before doing so. In my own code, I always try to follow his sound advice as he comes from the front lines :)

Upvotes: 2

Related Questions