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

2
  • 1
    stackoverflow.com/questions/4616202/… Commented Mar 27, 2013 at 18:22
  • 2
    Because in your example this is referring to the object referenced by horse? Commented Mar 27, 2013 at 18:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I think I do understand now why my attempt did not work. Still kind of digesting it... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.