1.定义基类与派生类
//定义基类
/*
* 类
* */
class myClass{
/*
* 构造函数
* */
constructor(x,y) {
// @ts-ignore
Object.assign(this,{x,y});//添加属性
}
}
//子类继续基类
class mySubClass extends myClass{
//构造
constructor() {
super(200,300);
}
//类实例方法
hello(){
console.log('hello,mySubClass');
}
}
2. 对象深浅克隆方法实现
//非继续克隆---浅克隆
let clone=(obj)=>{
// @ts-ignore
return Object.assign({},obj);
}
//继承克隆----深克隆
let clonedeep=(obj)=>{
let objProto = Object.getPrototypeOf(obj);
// @ts-ignore
return Object.assign(Object.create(objProto),obj);
}
3.实例化类对象并克隆
//实例化派生类并调用实例方法hello
let mysub = new mySubClass();
console.log(mysub,mysub.x,mysub.y);
mysub.hello();
//类对象克隆
let subClone = clone(mysub); //浅克隆
console.log(subClone);
//subClone.hello();//浅克隆hello方法没有克隆过来
let subDeepClone = clonedeep(mysub);//深克隆
console.log(subDeepClone);
subDeepClone.hello();//深克隆hello方法可克隆过来
4.通过反射调用类实例方法
// @ts-ignore
console.log( Reflect.has(subClone,'hello'));//false没有方法
// @ts-ignore
console.log( Reflect.has(subDeepClone,'hello'));//true 有hello方法
下面先确认对象有hello方法,然后再通过Reflect.get获得该方法并调用
// @ts-ignore
if(Reflect.has(subDeepClone,'hello')){ //如果对象存在hello这个属性名
// @ts-ignore
let func_hello = Reflect.get(subDeepClone,'hello');
// @ts-ignore
if(typeof (func_hello) == 'function'){ //如果hello是函数
console.log('通过反映执行函数===');
func_hello();//执行函数
}
}