Pregunta

Here is the code :

(function() {
    /*global casper:true */
   "use strict";

   this.run = function(casper) {
       // code test here
   };

   this.run(casper);
})();

casperjs test myfile.js returns :

TypeError: 'undefined' is not an object (evaluating 'this.run = function(casper) {

   }')
#    type: uncaughtError
#    error: "TypeError: 'undefined' is not an object (evaluating 'this.run = function(casper) {\n       \n   }')"

If I remove the "use strict", it simply hangs (expected behavior since this test is incomplete). I guess there's a rule I'm not understanding around the use strict, but the returned error doesn't make it obvious.

¿Fue útil?

Solución

In strict mode, this will be undefined inside an immediate function like that, and not the global object (which it would be without strict mode). One way to make your code work is to create the global variables explicitly (if that's what you're looking for):

window.run = function(casper) {
    // code test here
};
window.run(casper);

Or, if you're not looking for globals, just declare your method locally:

var run = function(casper) {
    // code test here
};

run(casper);

Otros consejos

In strict mode, "this" is not valid in functions that are not methods of an object. In non-strict mode, "this" refers to "window" in global functions like yours.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top