Typescript类对象深浅克隆与反射

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();//执行函数
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

自由软件开发者

有你的鼓励,我会更加努力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值