문제

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