Jim Andrews
Jim Andrews

Reputation: 375

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>

Upvotes: 5

Views: 707

Answers (2)

Aadit M Shah
Aadit M Shah

Reputation: 74204

Functions are objects in JavaScript. When you add properties to functions then they are not inherited by the instances of that function. However when you add properties to the prototype of the function then they are inherited. To understand how prototype-based inheritance works in JavaScript read the following answer.

Upvotes: 0

nrabinowitz
nrabinowitz

Reputation: 55678

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"

Upvotes: 8

Related Questions