5

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>
Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
Jim Andrews
  • 375
  • 1
  • 2
  • 14

2 Answers2

8

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"
nrabinowitz
  • 55,314
  • 10
  • 149
  • 165
  • 1
    The question is _why_ get_status is not added to myQuo. I already know that I added it to Quo, not to its prototype. – Jim Andrews Jul 26 '12 at 06:22
  • 5
    Instances do not inherit properties or methods of their constructors - only properties and methods attached to the prototype get inherited. – nrabinowitz Jul 26 '12 at 19:14
0

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.

Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299