执行“ ______未定义”,不确定原因

时间:2019-10-04 22:20:13

标签: javascript

我收到“未定义工作日”错误输出,不确定原因。任何帮助将不胜感激!

purchase_order = Purchase_order.objects.filter(query).order_by(id)[start: (start+length)]  

print(purchase_order.query)  

2 个答案:

答案 0 :(得分:3)

您的代码可能类似于:

var scopeMaster = function() {};

scopeMaster.prototype.testMethod = function() {

  (function(exports) {

    var days = ["monday", "tuesday", "wednesday", "thursday"];

    exports.name = function(number) {
      return days[number];

    };
    exports.day = function(name) {

      return days.indexOf(name);

    };

  })(this.weekday = {});

  console.log(weekday.name(1));

};

scopeMaster.prototype.testMethod();

它说“未定义工作日”,因为工作日搜索局部变量或父作用域中的变量。未在当前作用域对象中搜索成员,因此它与this.weekday不匹配。

您可以通过两种方式进行操作:

1)通过声明局部或父范围变量:

var scopeMaster = function() {};

var weekday = null; // here's the global one

scopeMaster.prototype.testMethod = function() {

  // var weekday = null; // if you want a private local one
  
  (function(exports) {

    var days = ["monday", "tuesday", "wednesday", "thursday"];

    exports.name = function(number) {
      return days[number];

    };
    exports.day = function(name) {

      return days.indexOf(name);

    };

  })(weekday = {});

  console.log(weekday.name(1));

};

scopeMaster.prototype.testMethod();

2)通过使用当前作用域成员变量:

var scopeMaster = function() {};

scopeMaster.prototype.testMethod = function() {
 
  (function(exports) {

    var days = ["monday", "tuesday", "wednesday", "thursday"];

    exports.name = function(number) {
      return days[number];

    };
    exports.day = function(name) {

      return days.indexOf(name);

    };

  })(this.weekday = {});

  console.log(this.weekday.name(1));

};

scopeMaster.prototype.testMethod();

答案 1 :(得分:0)

如果this参数中的this.weekday.name(1)值是对象数据类型(而不仅仅是undefined)但没有全局对象作为其值,则代码将按照报告的方式运行。

然后将在weekday对象上创建具有nameday方法的this属性,而不会出错,但是尝试将其作为全局属性变量进行访问将失败说weekday未定义。

如果代码在必需的节点模块中,则this answer解释为this设置为module.exports。如果不是这种情况,则需要研究this如何进一步获得其价值。