Parisitic inheritance in JavaScript

javascript

Solution

Why is that short circuit not working correctly (`secret = secret || {}`) in the `gizmo` function when not being passed a second parameter in the `hoozit` function (breaks in both Chrome and Firefox)??

Simple because you cannot access `secret` inside `that.test` because it does not exist in that scope:

function hoozit(id) {
  var that = gizmo(id);
  that.test = function (testid) {
    // secret is not defined in this or in any higher scope
    // hence you get a refernece error
    return testid === secret.id;
  };
  return that;
}

The only `secret` object that exists is local to the `gizmo` function.

If you define it and just don't pass it to `gizmo`, then `secret = secret || {}` will evaluate to `secret = {}`, i.e. a new object is created inside the `gizmo` function. That value is only accessible within the `gizmo` function and is not related at all to the `secret` variable in the `hoozit` function. The `secret` object inside `gizmo` is a different than the one in `hoozit`.

function hoozit(id) {
  var secret = {},      // secret object is created here
      that = gizmo(id);
  that.test = function (testid) {
    // you never set `secret.id`, hence the comparison results in `false`
    return testid === secret.id;
  };
  return that;
}

There is nothing wrong with `secret = secret || {}`, it is working as expected.

Problem

Watching a Douglas Crockford lecture on advanced JavaScript and he brings up the idea of parasitic inheritance which is essentially having constructors call other constructors to modify the object in question. Here is his code: ``` 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 ``` I understand the code and there is nothing too difficult to grasp here. The confusion takes place in the `hoozit` function. If you do not set `secret = {}` you will not get the a `true` being returned. This is baffling because in the `gizmo` function, you see `secret = secret || {}` which should take care of this for us... but it doesn't. Why is that short circuit not working correctly (`secret = secret || {}`) in the `gizmo` function when not being passed a second parameter in the `hoozit` function (breaks in both Chrome and Firefox)??

Original source