HopefullyHelpful HopefullyHelpful - 11 days ago 5
Javascript Question

How to declare member functions in javascript? Getting "TypeError: Object.function is not a function"

I'm coming from a java background and I'm trying to declare members in a java style way. Why are my functions not visible to the outside or not recognized as functions? What is the correct way to declare memberfunctions for a function from within the function?

function Animation() {
var draw = function draw() {
...
};

var move = function move() {
...
};
}

function startAnimation() {
...
var animation = new Animation();
function frame() {
...
animation.move()
animation.draw();
...
}
}


When executing the code I just get an error in the console:

TypeError: Object.function is not a function

Answer

If you'd like this to work as an instance method, you can also do

function Animation() {...}

Animation.prototype.move = function() {...};

Animation.prototype.draw = function() {...};

or with ES6

class Animation {

    constructor() {...}

    move() {
       ...
    }

    draw() {
       ...
    }
}
Comments