嗨, 大家好: 网站在新年后正式开通,欢迎大家加入我们,共同维护一个良好氛围的中国技术社区。 欢迎举报不良帖子,欢迎提供建议。
我们的QQ群:136102234,欢迎进群找答案,里边会有很多资深的大师们。 point overflow

来源segmentfault.com

    //方法1
    aSend:function() {
        ...
        reports.a.update(...);
    },

//方法2
bSend:function() {
    ...
    reports.b.update(...);
},

//方法3
cSend:function() {
    ...
    reports.c.update(...);
}

//有什么好的建议写成一个公共方法?(...基本没差别,有个别变量名改变)</code></pre>

asked 2016-03-18 15:34:48

jkant's gravatar image

jkant ♦♦
11135138139
accept rate: 3%


function send(flag, callback) {
  // 检测 reports[flag] 是否存在
  if (if reports[flag] && typeof reports[flag].update === "function") {
    reports[flag].update(callback);
  }
}

send("a", function (data) {
  console.info("success a:", data);
});
link

answered 2016-03-18 15:35:21

jkant's gravatar image

jkant ♦♦
11135138139
accept rate: 3%

//flag "a","b","c"...
function send(flag){
    reports[flag].update(...);
}
link

answered 2016-03-18 15:35:29

jkant's gravatar image

jkant ♦♦
11135138139
accept rate: 3%

公共方法,最好是封装成一个大的函数体,可以实现n个变量的,就好像那些分页插件,那种分装很好,代码重用率很高,不过需要很强的逻辑能力

link

answered 2016-03-18 15:35:37

jkant's gravatar image

jkant ♦♦
11135138139
accept rate: 3%

难道不是 reports[var].update(...);

link

answered 2016-03-18 15:35:44

jkant's gravatar image

jkant ♦♦
11135138139
accept rate: 3%

可以这样:

adcSend  function(flag){
//这里的flag代表传入参数,做个别修改
<!--差别部分-->
if(flag == "a"){
 //Todo
 //这里是a方法的个别修改
}else if(flag == "b"){
 //Todo
 //这里是b个别修改
}else {
//Todo
//这里是c个人修改
}
<!--这里是公共部分-->
//Todo
};
link

answered 2016-03-18 15:35:52

jkant's gravatar image

jkant ♦♦
11135138139
accept rate: 3%

Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×1

Asked: 2016-03-18 15:34:48

Seen: 804 times

Last updated: 2016-03-18 15:36:01

Related questions