【问题标题】:"use strict" makes my CasperJS test crashing if using this如果使用它,“use strict”会使我的 CasperJS 测试崩溃
【发布时间】:2013-01-19 07:15:36
【问题描述】:

代码如下:

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

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

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

casperjs test myfile.js 返回:

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   }')"

如果我删除“use strict”,它只会挂起(预期的行为,因为此测试不完整)。我想围绕 use strict 有一条我不理解的规则,但返回的错误并不明显。

【问题讨论】:

    标签: javascript casperjs use-strict


    【解决方案1】:

    在严格模式下,this 将在这样的立即函数中未定义,而不是全局对象(没有严格模式)。使您的代码工作的一种方法是显式创建全局变量(如果这是您要寻找的):

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

    或者,如果您不是在寻找全局变量,只需在本地声明您的方法:

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

    【讨论】:

      【解决方案2】:

      在严格模式下,“this”在不是对象方法的函数中无效。在非严格模式下,“this”指的是像你这样的全局函数中的“window”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-28
        • 1970-01-01
        • 1970-01-01
        • 2011-01-12
        • 2012-02-15
        • 1970-01-01
        • 1970-01-01
        • 2015-05-03
        相关资源
        最近更新 更多