语法错误在Javascript类中声明公共方法时

时间:2018-05-30 06:36:00

标签: javascript class

我在javascript中编写了一个类。当我尝试将方法声明为公共方法时,它给出了语法错误。我提供两种情况只有区别就是进入。

第一个案例显示语法错误:

var myclass=(function(){ 

function takeResponse(){.....}
.
.
.
function takeResponse(){.....}
      return  
      {
            takeResponse: takeResponse, 
            takeResponse_1: takeResponse_1, 
            takeResponse_2: takeResponse_2,
            takeResponse_3: takeResponse_3
      };
})();

第二个案例没有语法错误:

var TestUtils=(function(){

function takeResponse(URL)
{
    var Response=new Promise(function(resolve,reject){
        $.ajax({
            url: URL,
            type: "GET",
            dataType: "json",
            success: function(result){
                resolve(result);
            }
        });
    });
    return Response;
}

function takeResponse_1(URL,Data)
{
    var Response=new Promise(function(resolve,reject){
        $.ajax({
            url:URL,
            type: "POST",
            dataType: "json",
            data: JSON.stringify(Data),
            contentType: "application/json",
            success: function(result){          
                resolve(result);
            }
        });
    });
    return Response;
}

function takeResponse_2(URL,Data)
{
    var Response=new Promise(function(resolve,reject){
        var res = $.ajax({
            url: URL,
            type: "PUT",
            dataType: "json",
            data: JSON.stringify(Data),
            contentType: "application/json",
            async: false
        }).responseText;
        console.log("======"+res);
        resolve(res);
    });
    return Response;
}

function takeResponse_3(URL)
{
    var Response=new Promise(function(resolve,reject){
        var res = $.ajax({
            url: URL,
            type: "DELETE",
            dataType: "json",
            contentType: "application/json",
            async: false
        }).responseText;
        console.log("======"+res);
        resolve(res);
    });
    return Response;
}
return  {
    takeResponse: takeResponse, 
    takeResponse_1: takeResponse_1, 
    takeResponse_2: takeResponse_2,
    takeResponse_3: takeResponse_3
};
})();

我不知道为什么它在第一种情况下显示错误。 谁能告诉我这两个代码之间的区别? 提前致谢

1 个答案:

答案 0 :(得分:3)

这是因为javascript假设返回是在一行中完成的,并且在它之后附加;

 return ; 
      {
            takeResponse: takeResponse, 
            takeResponse_1: takeResponse_1, 
            takeResponse_2: takeResponse_2,
            takeResponse_3: takeResponse_3
      };

此行为称为自动分号插入, 阅读它here