Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crockford's code concerning the Constructor Invocation Pattern

The below code is almost identical to some code from Douglas Crockford's superb book JavaScript: The Good Parts, from pages 29-30. The only difference is that he adds the get_status property like so:

Quo.prototype.get_status=function() {
  this.status=string;
}

My question is why his code runs OK but my little change, below, results in an error that says myQuo has no get_status method?

<script>
  var Quo=function(string) {
    this.status=string;
  }
  Quo.get_status=function() {
    return this.status;
  }
  var myQuo=new Quo("confused");
  alert(myQuo.get_status());
</script>
like image 334
Jim Andrews Avatar asked Jul 26 '12 04:07

Jim Andrews


1 Answers

You're adding the method to the Quo function object, not to its prototype, so it will not be inherited by instances created with new Quo(). A function added in this way is a bit like a static method in classic OOP languages - it can be called with Quo.get_status(), but it won't be inherited by instances and this will refer to the Quo function itself.

Quo.status = "foo";
Quo.get_status(); // "foo"
like image 182
nrabinowitz Avatar answered Sep 30 '22 13:09

nrabinowitz