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.

有帮助吗?

解决方案

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);

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top