如何通过在JavaScript中提供方法作为参数来删除重复代码?下面是代码。
var toastrService = function (toastr) {
var _toastrService = this;
_toastrService.success =function(message,title) {
toastr.success(message,title);
}
_toastrService.info =function(message,title) {
toastr.info(message,title);
}
_toastrService.error =function(message,title) {
toastr.error(message,title);
}
_toastrService.warning =function(message,title) {
toastr.warning(message,title);
}
_toastrService.success =function(message,title) {
toastr.success(message,title);
}
}
答案 0 :(得分:0)
只需遍历一组属性字符串:
['success', 'info', 'error', 'warning', 'success'].forEach((prop) => {
_toastrService[prop] = function(message, title) {
toastr[prop](message, title);
};
});
如果您不需要去除多余的函数参数,则可以将其调整为:
['success', 'info', 'error', 'warning', 'success'].forEach((prop) => {
_toastrService[prop] = toastr[prop].bind(toastr);
});
如果函数不需要this
中的toastr
,则可以省去.bind
并分配简单的函数:
_toastrService[prop] = toastr[prop]
答案 1 :(得分:0)
要使全局属性可注入,只需将其声明为AngularJS值:
string command="DELETE FROM AuditLog WHERE ID = 'ea53b72a-4ab2-4f88-8f1d-0f96baa7cac7'";
context.Database.ExecuteSqlCommand(command);
然后将其注入到需要的地方:
angular.module("app",[]).value("toastrService", toastr);
有关更多信息,请参见