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>
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With