Javascript: prototype method error?

I get the error "TestFunc not defined" 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 (); } 

... is launched from this bit of code:

 /* index.js */ var myObj = new MyObject ('test'); myObj.RealFunc (); // Firebug: "TestFunc is not defined" 
+4
source share
2 answers
 // 1. this.TestFunc (); 

It's good. This will work, and other calls will be deleted.

(Well, this works until you separate RealFunc from its owner and call it yourself, for example var method= myObj.RealFunc; method(); or through an event handler or timeout. In this case, this in RealFunc will not be an instance of MyObject, and you will need to look at the closure or Function.bind to make it work.)

 // 2. TestFunc (); 

No, TestFunc is not defined as a variable in a local or global scope. This causes the error you get from Firebug.

 // 3. (I didn't really think this would work, // but thought it was worth a try...) MyObject.TestFunc (); 

No, you were right. :-) It will be MyObject.prototype.TestFunc.call(this) , done explicitly.

JavaScript confuses things a bit by placing some of the same methods on standard constructor functions for built-in objects as on their prototypes (for example, String.split exists where really only String.prototype.split should). But this does not happen with your own objects unless you explicitly say something like MyObject.TextFunc= MyObject.prototype.TextFunc .

+3
source

Option 1 seems correct. I tried your code in ExecuteJS and skipped 2. and 3., it worked (although I deleted the console.log call and changed it to alert ). TestFunc is called inside RealFunc .

What happens if you remove "use strict"; ?

+1
source

Source: https://habr.com/ru/post/1300429/


All Articles