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

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

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

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


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


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());

笑~


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();

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


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


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

window.myawesometool = (function (){
  var x, y, z; //private properties
  return {
    methodA: function() {
    },
    methodB: function() {
    }
  }
})();
【热门文章】
【热门文章】