在封装地图前端API时,一开始在多层次深对象中无法获取类的实例变量,一开始用prototype上的一个属性代替,但是无法满足多个地图实例启动的要求,因为prototype属性是共享的。以下有三种解决方法。
在运行时绑定
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function SubRun(input){ this._input=input; } SubRun.prototype.funs=function(){ const self=this; return{ show:function(){ console.log(self._input); } } } let subRun=new SubRun("sub_run_example"); subRun.funs().show();
|
通过闭包返回一个函数可获取运行时指向实例的this,但是方法调用时多了一个括号,稍显麻烦。
使用Apply
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| function SubApply(input){ this._input=input; SuperApply.apply(this,arguments); } function SuperApply(input){ const self=this; this._input=input; this.base= { show:function(){ console.log("from param: "+input); console.log("from self: "+self._input); } }; this.funs={ show:function(){ console.log("from funs:"); self.base.show(); } }; } let subApply=new SubApply("sub_apply_example"); subApply.base.show(); subApply.funs.show();
|
改方法可解决this对象获取的问题,但是定义多个proto属性需重复写,不优雅。
使用Classs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| class SuperClass{ constructor(input){ this._input=input; const self=this; this.base= { show:()=>{ console.log("from param: "+input); console.log("from self: "+this._input); } }; this.funs={ show:function(){ console.log("from funs lambda:"); self.base.show(); } }; } get self(){ return this; } get protoPropterty(){ return { property:()=>{ this.protoMethod(); console.log(this._input); } } } protoMethod(){ console.log("from proto :"+this._input); } } class SubClass extends SuperClass{ constructor(input){ super(input); this._input=input; this.ori={ display:()=>{ console.log("from sub call"); this.funs.show(); } } } }
let subClass=new SubClass("sub_class_example"); let subClass2=new SubClass("sub_class_example2");
subClass.protoPropterty.property();
|
若有多个原型属性,用const self=this
的方法稍显繁琐,利用lambda的特性可在多层次深对象中直接获取指向实例的this。