I’m running into problems when I’m trying to call a function on an object from within that same object. I’ve read that calling a function on an object from within that object is possible here, so I think it must be my use of prototype that’s causing the issue. Here’s an example:
function Foo() {
this.DoStuff();
}
Foo.prototype.DoStuff = function() {
alert("I'm frantically doing stuff!");
}
That code (or something very similar) just doesn’t want to work. Any ideas why?
What you have should work fine. It’s important to remember that the value of
thisdepends on how you call the function. For it to work as you expect, you need to use thenewoperator to call the function as a constructor:Here’s a working example.
If you call the function like normal,
thisrefers to the global object, which doesn’t have aDoStuffproperty, so a TypeError is thrown. Here’s a broken example.