如何在相同的“返回值对象”中访问javascript函数且父函数未命名。
这是一个代码示例
function ($http, $rootScope, $timeout, $location, config, $q, sessionService) {
return {
_get_user_approval_mode: function (data) {
var defer = $q.defer();
this.prepareHttpCall($http, true);
$http.post(config.CLIENT_API_ROOT + 'user-approval-mode', {
params: data
})
.then(function (response) {
defer.resolve(response);
}).catch(function (error) {
if (error_handler(error) === "") { //Getting on this line since error_handler() is undefined
defer.reject(error);
}
});
return defer.promise;
},
error_handler(error) {
console.log('error received in handler');
console.log(error);
if (error.status == "400") {
$('#somethingWrong').modal('show');
$rootScope.errorHandleMessage = error.data.reason;
} else if (error.status == "401" && error.data.message == "Unauthorized" || error.status == "401" && error.data.message == "The incoming token has expired") {
// $('body').removeClass('modal-open');
// $('.modal-backdrop').remove();
$location.path('/login');
} else if (error.status + "".match('5\d{2}')) {
$('#somethingWrong').modal('show');
$rootScope.errorHandleMessage = "Sorry! something went wrong, please try after sometime.";
} else {
return "";
}
return "error handled";
}
}
}
当我尝试调用'error_handler'函数时,在函数'_get_user_approval_mode'中收到未定义的错误-如上述代码中所述。
答案 0 :(得分:1)
不知道如何调用_get_user_approval_mode
(即不知道其this
的值),“最安全”的解决方案是将对象分配给变量并访问该变量:
function ($http, $rootScope, $timeout, $location, config, $q, sessionService) {
var obj = {
_get_user_approval_mode: function (data) {
var defer = $q.defer();
this.prepareHttpCall($http, true);
$http.post(config.CLIENT_API_ROOT + 'user-approval-mode', {
params: data
})
.then(function (response) {
defer.resolve(response);
}).catch(function (error) {
if (obj.error_handler(error) === "") {
defer.reject(error);
}
});
return defer.promise;
},
error_handler(error) {
// ...
}
};
return obj;
}
但是,如果error_handler
实际上不是对象上的方法,因为它不是从其他代码中调用的,则将其定义为单独的函数会更有意义。