简体   繁体   English

使用JavaScript oop减少代码重复

[英]Reduce code duplication using javascript oop

I have a javascript code which contains more number of functions. 我有一个JavaScript代码,其中包含更多功能。 inside each functions code looks similar. 每个函数内部的代码看起来相似。 Is there any way to reduce and optimize the code using javascript oop. 有没有办法使用javascript oop减少和优化代码。 So my script goes like this. 所以我的脚本是这样的。

function cal_a() {
    var a_list = [];
  function fetch_dom() {
    var a = document.getElementById("pOne");
    a.innerHTML = "Hello";
    a_list.push("Hello");
  }
  fetch_dom();
}
function cal_b() {
    var b_list = [];
  function fetch_dom() {
    var b = document.getElementById("pTwo");
    b.innerHTML = "World";
    b_list.push("World");
  }
  fetch_dom();
}
cal_a();
cal_b();
//..
//..
//..
//cal_z();

HTML code looks HTML代码外观

<p id="pOne"></p>
<p id="pTwo"></p>

Please pardon me if the question is wrong. 如果问题有误,请原谅我。 Thanks in advance. 提前致谢。

Sure, pull out the common parts and make a function which returns a function. 当然,请拉出公用部分,并制作一个可以返回功能的功能。

function make_cal(elem_id, text) {
    return function() {
        var list = [];
      function fetch_dom() {
        var b = document.getElementById(elem_id);
        b.innerHTML = text;
        list.push(text);
      }
      fetch_dom();
    }
}

let cal_a = make_cal("pOne", "Hello");
let cal_b = make_cal("pTwo", "World");

I have to say the list doesn't do anything here 我不得不说列表在这里没有任何作用

function cal(id, text) {
  var list = [];
  function fetch_dom() {
    var el = document.getElementById(id);
    el.innerHTML = text;
    list.push(text);
  }
  fetch_dom();
}

cal('id', 'text');

The fetchDom is better to be placed on object constructor: 最好将fetchDom放在对象构造函数上:

function Cal(elClass, text) {
  this.list = [];
  this.elClass = elClass;
  this.text = text;
}

Cal.prototype.fetchDom = function() {
  var el = document.getElementById(this.elClass);
  el.innerHTML = this.text;
  this.list.push(el);
};

var calA = new Cal("pOne", "Hello");
var calB = new Cal("pTwo", "World");

calA.fetchDom();
calB.fetchDom();

Then you can access your lists by: 然后,您可以通过以下方式访问列表:

calA.list;
calB.list;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM