cari

Rumah  >  Soal Jawab  >  teks badan

javascript - JS如何写一个工具类!?有最优实现吗?只看代码!

在做一些地图的功能,使用高德地图,自然地想对一些比如画线,搜索,经纬度标记的功能做个工具类,方便这个模块用完在其他模块继续用。

不考虑其他,这个工具类有什么好的写法吗?不要思想和思路,只看代码,一个很简单的demo说明最好~

阿神阿神2897 hari yang lalu518

membalas semua(5)saya akan balas

  • 大家讲道理

    大家讲道理2017-04-10 14:28:04

    笑~


    var tools = { // you can have any properties prop1: ..., prop2: ..., ... // you can have any methods tool1: function () { ... }, tool2: function () { var _p1 = this.prop1; // you can reference your properties this.tool1(); // you can call your methods }, ... }; // no matter where you are, just use it! var p = tools.prop1; tools.tool2();

    没思想,没思路,没最佳实践,就是简单、能用。

    balas
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-10 14:28:04

    不要思想和思路,只看代码。
    请让我偷笑3分钟。

    balas
    0
  • 阿神

    阿神2017-04-10 14:28:04

    很明显,你需要的是高大上单例闭包对象定义方法:

    window.myawesometool = (function (){
      var x, y, z; //private properties
      return {
        methodA: function() {
        },
        methodB: function() {
        }
      }
    })();
    

    balas
    0
  • 天蓬老师

    天蓬老师2017-04-10 14:28:04

    var Tool = function(a, b, c) {
        this.a = a;
        this.b = b;
        this.c = c;
    };
    
    Tool.prototype.aabbcc = function() {
        return this.a + this.b + this.c;
    };
    
    var tool = new Tool(1, 2, 3);
    console.log(tool.aabbcc());
    

    balas
    0
  • 高洛峰

    高洛峰2017-04-10 14:28:04

    工具类感觉还是 还是单例闭包合适,又不是组件 没必要 用面向对象

    balas
    0
  • Batalbalas