消除重复代码的最佳方法是什么?
let BaseErrorResponse = function(mes, rti, rsi, st) {
return {
"message": msg,
"response_type_id": rti,
"response_status_id": rsi,
"status": st
}
};
let InvalidParamResponse = function(mes, rti, rsi, st, ip) {
return {
"message": msg,
"response_type_id": rti,
"response_status_id": rsi,
"status": st,
"invalid_params": ip
}
};
let SuccessResponse = function(msg, rti, rsi, st, data) {
return {
"message": null,
"response_type_id": null,
"response_status_id": null,
"status": null,
"data": {}
}
};发布于 2016-02-13 16:03:04
那么,由于您正在使用ES2015 (又名ES6),似乎class对您来说是一个有效的选择:
class BaseErrorResponse {
constructor(mes, rti, rsi, st) {
this.message = msg;
this.response_type_id = rti;
this.response_status_id = rsi;
this.status = st;
}
}
class InvalidParamResponse extends BaseErrorResponse {
constructor(mes, rti, rsi, st, ip) {
super(mes, rti, rsi, st);
this.invalid_params = ip;
}
}
class SuccessResponse extends BaseErrorResponse {
constructor(msg, rti, rsi, st, data) {
super(null, null, null, null); // Why the nulls when you're passing
// those args in?
this.data = {}; // Didn't you mean = data here?
}
}根据你对我对这个问题的评论的答复,最后一个问题是:
class SuccessResponse extends BaseErrorResponse {
constructor(msg, rti, rsi, st, data) {
super(msg, rti, rsi, st);
this.data = data;
}
}发布于 2016-02-13 16:02:37
你只需要合并对象
let BaseErrorResponse = function(mes, rti, rsi, st) {
return {
"message": msg,
"response_type_id": rti,
"response_status_id": rsi,
"status": st
}
};
let InvalidParamResponse = function(mes, rti, rsi, st, ip) {
return Object.assign(BaseErrorResponse(mes, rti, rsi, st), {
"invalid_params": ip
});
};
let SuccessResponse = function(mes, rti, rsi, st, data) {
return Object.assign(BaseErrorResponse(mes, rti, rsi, st), {
"data": {}
});
};不过,将它们转换为彼此继承的实际构造函数可能是个好主意。
function BaseErrorResponse(mes, rti, rsi, st) {
this.message = msg;
this.response_type_id = rti;
this.response_status_id = rsi;
this.status = st;
}
function InvalidParamResponse(mes, rti, rsi, st, ip) {
BaseErrorResponse.call(this, mes, rti, rsi, st);
this.invalid_params = ip;
}
InvalidParamResponse.prototype = Object.create(BaseErrorResponse.prototype);
InvalidParamResponse.prototype.constructor = InvalidParamResponse;
function SuccessResponse(mes, rti, rsi, st, data) {
BaseErrorResponse.call(this, mes, rti, rsi, st);
this.data = data;
}
SuccessResponse.prototype = Object.create(BaseErrorResponse.prototype);
SuccessResponse.prototype.constructor = SuccessResponse;发布于 2016-02-13 16:09:40
对我来说,一个更简单的解决方案是:
var BaseErrorResponse = function(mes, rti, rsi, st) {
return { mes, rti, rsi, st };
};
var InvalidParamResponse = function(mes, rti, rsi, st, ip) {
var response = BaseErrorResponse(mes, rti, rsi, st);
response.invalid_params = ip;
return response;
};
var SuccessResponse = function() {
var response = BaseErrorResponse(null, null, null, null);
response.data = {};
return response;
};https://stackoverflow.com/questions/35381974
复制相似问题