1. 程式人生 > >typescript中繼承Array、Map、Set報錯的解決

typescript中繼承Array、Map、Set報錯的解決

if(不支援Map){
	//polyfill
}else{
	(function(){//可繼承Map替代原生Map
		var GMap=globalThis.Map;
		try{
			Map.call({});
		}catch(e){
			globalThis.Map=function(args){
				var map=new GMap(args);
				Object.setPrototypeOf(map,Object.getPrototypeOf(this));
				return map;
			};
			Map.prototype=GMap.prototype;
		}
	})();
}
if(不支援Set){
	//polyfill
}else{
	(function(){//可繼承Set替代原生Set
		var GSet=globalThis.Set;
		try{
			Set.call({});
		}catch(e){
			globalThis.Set=function(args){
				var set=new GSet(args);
				Object.setPrototypeOf(set,Object.getPrototypeOf(this));
				return set;
			};
			Set.prototype=GSet.prototype;
		}
	})();
}

Array要改的地比較多,

(function(){//可繼承的Array替換原生Array
	var GArray=globalThis.Array;
	function Array(){
		var arr=GArray.apply(this,arguments);
		if(this.constructor===GArray){//new呼叫
			return arr || this;
		}else{//super呼叫
			this.length=arr.length;
			Object.assign(this,arr);
		} 
	}
	Array.prototype=GArray.prototype;
	Array.from=GArray.from;
	Array.of=GArray.of;
	Array.isArray=GArray.isArray;
	globalThis.Array=Array;
})();

除了替換原生Array還需修改繼承函式,供參考

var __extends;
if(!Object.getPrototypeOf){
	__extends=function(clazz,superClazz){
		Object.assign(clazz,superClazz);
		clazz.prototype=superClazz===Array?Sky.createArrayPrototype():Object.create(superClazz.prototype);
		clazz.prototype.constructor=clazz;
	};
	Sky.createArrayPrototype=function(){
		var arr=Sky.pick(Array.prototype,["concat","join","pop","push","reverse","shift","slice","sort","splice","toString","unshift"]);
		Object.assign(arr,Array.prototype);
		arr.length=0;
		return arr;
	};
}