[英]Alternative method for function in javascript
I would like to know is there any alternative method for a function in my scenario in javascript我想知道在我的 javascript 场景中是否有任何替代函数的方法
Below function works fine, but is there any alternative method to do, since there are more obj
下面的函数工作正常,但是有没有其他方法可以做,因为有更多的obj
//will get single object as response as anyof these
obj ={"id":"trans", "cn": "SG", "ccy": "SGD"};
obj ={"id": "remit", "cn": "TH", "ccy": "THB"};
obj ={"id": "fund", "cn": "IN", "ccy": "INR"};
function getTrans(){
var value = 1000;
var rate = 0.5;
return value * rate;
}
function getFund(){
var value = 2000;
var rate = 0.2;
return value * rate;
}
var result = getData(obj);
function getData(obj){
if(obj.id==="trans"){
return getTrans(obj);
}
else if(obj.id==="fund"){
return getFund(obj);
}
else{
return obj;
}
}
You would usually write a map letting you access your function, for example例如,您通常会编写一个地图让您访问您的功能
//will get object as response
var obj ={"id":"trans", "cn": "SG", "ccy": "SGD"};
var obj ={"id": "remit", "cn": "TH", "ccy": "THB"};
var obj ={"id": "fund", "cn": "IN", "ccy": "INR"};
const extractors = {
trans(obj) {
var value = 1000;
var rate = 0.5;
return value * rate;// this should probably use obj
},
fund(obj) {
var value = 2000;
var rate = 0.2;
return value * rate;
}
}
function getData(obj){
let extractor = extractors[obj.id];
return extractor ? extractor(obj) : obj;
}
var result = getData(obj);
If you have other similar functions to associate to your ids, you could use objects instead of functions:如果您有其他类似的函数与您的 id 相关联,您可以使用对象而不是函数:
const handlers = {
trans: {
getData: obj => ...,
foo: obj => ...
},
...
and then access the functions with然后使用
function getData(obj){
let handler = handlers[obj.id];
return handler ? handler.getData(obj) : obj;
}
This kind of pattern is very extensible and is suited to injections, meaning you can have a global getData code not aware of the various types, but other parts of your applications registering new handlers.这种模式非常可扩展并且适合注入,这意味着您可以拥有一个不知道各种类型的全局 getData 代码,但是您的应用程序的其他部分注册了新的处理程序。
class ObjX{ constructor(id,cn,ccy){ this.id=id; this.cn=cn; this.ccy=ccy; } trans=function(){ var value = 1000; var rate = 0.5; return value * rate; } fund=function(){ var value = 2000; var rate = 0.2; return value * rate; } getData(){ if(this[this.id]){ return this[this.id](); }else{ return this; } } } obj =new ObjX("trans","SG","SGD"); obj2 =new ObjX("remit","TH","THB"); obj3 =new ObjX("fund","SG","INR"); console.log(obj.trans()); console.log(obj.getData()); console.log(obj2.getData()); console.log(obj3.getData());
Try this magic!试试这个魔法!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.