I am getting a “TestFunc is not defined” error when this bit of code…
/* my_object.js */
"use strict";
function MyObject (param) {
this.param = param;
}
MyObject.prototype.TestFunc = function () {
console.log ('in TestFunc');
}
MyObject.prototype.RealFunc = function () {
// I have tried 3 different ways to call TestFunc:
// 1.
this.TestFunc ();
// 2.
TestFunc ();
// 3. (I didn't really think this would work,
// but thought it was worth a try...)
MyObject.TestFunc ();
}
…gets run from this bit of code:
/* index.js */
var myObj = new MyObject ('test');
myObj.RealFunc (); // Firebug: "TestFunc is not defined"
That’s fine. That’ll work, with the other calls removed.
(Well, it works as long as you don’t peel off the
RealFuncfrom its owner and call it on its own, likevar method= myObj.RealFunc; method();or via an event handler or timeout. In that casethisin RealFunc wouldn’t be the MyObject instance and you’d need to look at closures orFunction.bindto get it to work.)Nope, TestFunc is not defined as a variable in local or global scope. This causes the error you get from Firebug.
No, you were right. 🙂 It would be
MyObject.prototype.TestFunc.call(this), done explicitly.JavaScript does kind of confuse the matter by putting some of the same methods on the standard constructor functions for built-in objects as on their prototypes (for example
String.splitexists where really onlyString.prototype.splitshould). But that doesn’t happen to your own objects unless you explicitly say something likeMyObject.TextFunc= MyObject.prototype.TextFunc.