Reputation: 75
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
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
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:
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();
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