The title may sound a bit confusing. Please allow me to cast Crockford's constructor into the following simple example and create objects using two different ways. (Browser is FireFox.)
var car = function(carSpec) {
var maker = carSpec.maker;
var year = carSpec.year;
var that = {};
that.getMaker = function () {
return maker;
};
that.getYear = function () {
return year;
};
return that;
};
One way to create an object, as Crockford pointed out, is to use Object.create
method,
myCar = Object.create(car({maker: 'Nissan', year: 2004}));
console.log(myCar); // Object {}, on FireFox console.
and the methods getMaker
and getYear
are attached to the __proto__
.
The other way is to invoke car
and let it return an object
yourCar = car({maker: 'Ford', year: 2010});
console.log(yourCar); // Object { getMaker: car/that.getMaker(), getYear: car/that.getYear() }
and methods getMaker
and getYear
becomes the own properties of object yourCar
.
My questions is: What are the pros and cons of these two ways of object creation from this "Crockford constructor"?