evanr123
evanr123

Reputation: 75

"______ is not defined" execption, not sure why

I am getting "weekday is not defined" error output, not sure why. Any help is greatly appreciated!

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

Upvotes: 0

Views: 98

Answers (2)

traktor
traktor

Reputation: 19301

The code behaves as reported if the this value in the this.weekday.name(1) parameter is an object data type (and not just undefined) but does not have the global object as its value.

A weekday property with name and day methods will then be created on the this object without error, but attempts to access it as a global property variable will fail saying weekday is not defined.

If the code is in a required node module, this answer explains that this is set to module.exports. If this is not the case you will need to investigate how this gets its value further.

Upvotes: 0

Taha Paksu
Taha Paksu

Reputation: 15616

Your code is probably something like:

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

it says "weekday isn't defined" because weekday searches for a local variable, or a variable in the parent scopes. Not searching a member in the current scope object, and thus it won't match this.weekday.

You can do it in two ways:

1) By declaring a local or parent scope variable:

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) By using the current scope member variable:

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

Upvotes: 3

Related Questions