Just finished a Douglas Crockford lecture where he introduced the concept of parasitic inheritance in JavaScript. This involves one constructor calling another to modify the object. The code example he provided is:
function gizmo(id, secret) {
secret = secret || {};
secret.id = id;
return {
toString: function () {
return "gizmo " + secret.id;
}
};
}
function hoozit(id) {
var secret = {},
that = gizmo(id, secret);
that.test = function (testid) {
return testid === secret.id;
};
return that;
}
var myHoozit = hoozit(20);
console.log(myHoozit.test(20)); //returns true
The code seems pretty straightforward except for one thing - the hoozit
function raises confusion. Without setting secret = {}
, you won't get a true
returned. This puzzles me because in the gizmo
function, there's secret = secret || {}
which should handle this scenario... but it doesn't.
Why does the short circuit (secret = secret || {}
) fail in the gizmo
function when no second parameter is passed in the hoozit
function (breaks in Chrome and Firefox)??