0

I am trying to do something kind of polymorphic object oriented in Javascript where I have a map of object 'types' and each one has its own properties and functions which I can call.

While the properties work fine the functions do not and I cant understand why. In Firefox I get the error: TypeError: this.functionmap[type].action is not a function

Here is my code:

var object = {
    flapWings : function(count) { alert("I am flapping my wings "+count+" times"); },
    kick : function(count) { alert("I am kicking my legs "+count+" times"); },
    functionmap : {
        "bird" : { label : "Bird", action : this.flapWings },
        "horse" : { label : "Horse", action : this.kick }
    },
    doAction : function (type, count) {
         alert("I am a "+this.functionmap[type].label);
         this.functionmap[type].action(count);
    }
};

object.doAction("horse", 5);

Here is JSFiddle example:

http://jsfiddle.net/JKvyP/

I just dont see why: action : this.kick is not getting a reference to the kick function created right above it!

I want to avoid something stupid like action : function(count) : this.kick(count); even though that doesnt work either - I want a direct reference without having to retype the parms

Trant
  • 3,461
  • 6
  • 35
  • 57

1 Answers1

1

You can't magically pass parameters to a function that is just referenced, so you'll need some anonymous functions, and referencing the object directly within that scope etc :

var object = {
    flapWings : function(count) { 
        alert("I am flapping my wings "+count+" times"); 
    },
    kick : function(count) {
        alert("I am kicking my legs "+count+" times"); 
    },
    functionmap : {
         "bird" : { 
                   label : "Bird", 
                   action : function(param) {
                                object.flapWings(param);
                           }
                  },
        "horse" : { 
                   label : "Horse", 
                   action : function(param) {
                               object.kick(param);
                            }
                   }
    },
    doAction : function (type, count) {
         alert("I am a "+this.functionmap[type].label);
         this.functionmap[type].action(count);
    }
};

object.doAction("horse", 5);

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Thank you, I think I do understand now why my attempt did not work. Still kind of digesting it... :) – Trant Mar 27 '13 at 18:42