2017-04-26 128 views
0

我从下面的代码中获得期望的输出。这些是打印数据JavaScript函数不能从另一个函数调用

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

但是当我尝试这样的事情在另一个page.I没有得到期望的输出两个JavaScript函数表达式。

这是我的代码。

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不是函数 请大家帮忙。

+2

移动'变种的getData =函数(URL){''以上变种employeesList = {' –

+0

确保功能在[范围]中所定义或可访问的(https://scotch.io/tutorials/understanding-范围式的JavaScript)。 – Ninjaneer

+0

或者声明它像'function functionName(){}'而不是使用变量。这样它才能在声明之前可用。 – Hissvard

回答

1
  • 不能使用一个变量之前定义它,所以你必须employeesList
  • 之前声明getData变量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();

我希望很清楚,再见。

0

有两种方法来定义 “功能”:

  1. 变种FUNC_NAME =函数(){...}
  2. 功能FUNC_NAME(){...}

的不同的是,当你使用第二个时,它可以在声明之前被调用。

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

    //var getData = function (url) { 
function getData (url) { // <====== change to this 
    var error = false; 

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

    }); 
};