gpt4 book ai didi

JavaScript 函数不能相互调用

转载 作者:行者123 更新时间:2023-12-03 04:27:45 25 4
gpt4 key购买 nike

我从下面的代码中得到了所需的输出。这是两个用于打印数据的 JavaScript 函数表达式

(function(){
var getData=function()
{
console.log("getdata");
},
setData=function()
{
getData();
console.log("setData");
};
setData();
})();

但是当我在另一个页面中尝试类似的操作时,我没有得到所需的输出。

这是我的代码。

var employeesList = {
getemployees: function () {
var data= getData("Employees/GetEmployees");
},
init: function () {
this.getemployees();
}
}.init();

var getData = function (url) {
var error = false;

$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function (data) {
return data;
},
error: function () {
return error = true;
}

});
};

我遇到这样的错误。getData 不是一个函数请帮忙。

最佳答案

  • 在定义变量之前不能使用它,因此必须声明 getData之前employeesList
  • 变量 datagetemployees无法访问,我在那里添加了一个返回,因此您可以在 init 中使用它的值

var getData = function (url) {
var error = false;

/*$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function (data) {
return data;
},
error: function () {
return error = true;
}

});*/
return 'test_result';
};

var employeesList = {
getemployees: function () {
//Here you should return the result
return getData("Employees/GetEmployees");
},
init: function () {
var res = this.getemployees();
console.log(res);
}
}.init();

我希望这是清楚的,再见。

关于JavaScript 函数不能相互调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43626795/

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