gpt4 book ai didi

javascript - "______ is not defined"异常,不知道为什么

转载 作者:行者123 更新时间:2023-11-28 16:58:54 26 4
gpt4 key购买 nike

我收到“工作日未定义”错误输出,不知道为什么。非常感谢任何帮助!

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

最佳答案

您的代码可能类似于:

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

关于javascript - "______ is not defined"异常,不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58243720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com