lilHar
lilHar

Reputation: 1866

member function isn't a function error

With this code:

function thing(){
    function majig(){
        alert("done");
    }
}
var mything = new thing();
mything.majig();

I'm getting this error: TypeError: mything.majig is not a function

I've done javascript for some time, and I've done functions as part of functions and called them before. I know it has to be something simple I'm missing or forgetting, but various websearches (and poking around here) are getting me deeper theory answers, or examples that seem to indicate that this should work.

I know TypeError: foo is not a function usually means a syntax error. I've looked up examples, and it looks like I have the syntax right (I've tried a few variations with no success).

It's got to be some dumb simple mistake, but I'm just not catching it right now. What do I do in my function to make the mything.majig(); run properly?

Upvotes: 0

Views: 175

Answers (2)

slebetman
slebetman

Reputation: 113926

The syntax is not what you think it means. It's not a member declaration. It's an inner function. Inner functions work just like local variables - they're only accessible in the scope of the outer function:

function foo () {
    function bar () {}
    bar(); // accessible here
}
bar(); // undefined here

If your function is a constructor, then to add a member function to the object that it constructs you'd add it to the constructor's prototype:

function Foo () {}
Foo.prototype.bar = function () {}; // bar is a member of object Foo

var f = new Foo();
f.bar(); // call member function

Objects in javascript are dynamic. They behave more like maps/hashes do in other languages. This means you can add a member function directly to an object instead of a constructor's prototype:

var f = {};
f.bar = function () {};

f.bar(); // call member function

Following the logic above, since this in a constructor refers to the object being constructed, you can also dynamically add a function to this. This is typically called "decoration" since it is effectively an ad-hoc version of the decorator design pattern:

function Foo () {
    this.bar = function () {}
}

var f = new Foo();
f.bar();

Upvotes: 2

Jacob
Jacob

Reputation: 78860

You have declared a function in thing, but it's not attached to this at all. Try this:

function thing(){
    this.majig = function() {
        alert("done");
    }
}

var mything = new thing();
mything.majig();

Alternately:

function thing() {
  return {
    majig: function() {
      alert("done");
    }
  };
}

Or, better yet:

function thing() { }
thing.prototype.majig = function () {
  alert('done');
}

Upvotes: 3

Related Questions