1

Why does this piece of code give me a error "Uncaught TypeError: Cannot set property 'grossSuperAnnuation' of undefined "? Thanks.

function taxCalculation(configuration){
      this.superAnnuationPercentage = configuration.superAnnuationPercentage;
      this.superAnnuationTaxRate    = configuration.superAnnuationTaxRate;
};

var tax = new taxCalculation({
    superAnnuationPercentage: 9.25,
    superAnnuationTaxRate:  15
});

tax.prototype.grossSuperAnnuation = function(income){
    return income * this.superAnnuationPercentage / 100;

};
Huangism
  • 16,278
  • 7
  • 48
  • 74
andrew_b
  • 29
  • 1
  • 4
  • because prototype is property of constructor. But every object has link to its constructor. So you can do following `tax.constructor.prototype.grossSuperAnnuation = function() { ... }` – Evgeniy Sep 04 '14 at 12:58
  • Not sure why you would set shared behavior on an instance. Do you want to confuse yourself and future programmers working on your code? More info on constructor functions and prototype here: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Sep 04 '14 at 13:42

1 Answers1

2

The prototype you want to change is the one of your constructor :

taxCalculation.prototype.grossSuperAnnuation = function(income){

If you really want to start from the instance, you could do this :

tax.constructor.prototype.grossSuperAnnuation = function(income){

Note that you could do

tax.grossSuperAnnuation = function(income){

but then only this instance would have that function, not the other ones created with new taxCalculation.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758