博客
关于我
对于类的构造函数的this.XXX=XXX写起来麻烦,使用proxy来偷懒
阅读量:669 次
发布时间:2019-03-15

本文共 936 字,大约阅读时间需要 3 分钟。

//创建用户类class User {    //对于写个给太麻烦了    // constructor(firstName,lastName,age) {    //     this.firstName=firstName;    //     this.lastName=lastName;    //     this.age=age;    // }}/** * 直接对构造函数进行代理 * @param Class 对象 * @param propNames 对应构造函数的参数 * @returns {any} * @constructor */function ConstructorProxy(Class, ...propNames) {    return new Proxy(Class, {        construct(target, argumentsList) {            const obj = Reflect.construct(target, argumentsList)            propNames.forEach((name, i) => {                obj[name] = argumentsList[i];            })            return obj;        }    })}const UserProxy = ConstructorProxy(User, "firstName", "lastName", "age")console.log(UserProxy)const obj = new UserProxy("w", "q", 18);console.log(obj)//创建Monster类class Monster {}const MonsterProxy = ConstructorProxy(Monster, "attack", "defence", "hp", "rate", "name")const m = new MonsterProxy(10, 20, 100, 30, "怪物")console.log(m);

 

 

 

转载地址:http://rsamz.baihongyu.com/

你可能感兴趣的文章
MySQL修改密码报错ERROR 1396 (HY000): Operation ALTER USER failed for ‘root‘@‘localhost‘
查看>>
Mysql全局优化参数
查看>>
MySQL全文索引实现简单版搜索引擎
查看>>
MySQL全面瓦解:安装部署与准备
查看>>
mysql共享锁与排他锁
查看>>
MySQL内存表使用技巧
查看>>
MySQL再叙(体系结构、存储引擎、索引、SQL执行过程)
查看>>
mysql出现错误的解决办法
查看>>
MySQL函数
查看>>
mysql函数汇总之字符串函数
查看>>
mysql函数汇总之数学函数
查看>>
mysql函数汇总之日期和时间函数
查看>>
mysql函数汇总之条件判断函数
查看>>
mysql函数汇总之系统信息函数
查看>>
MySQL函数简介
查看>>
mysql函数遍历json数组
查看>>
MySQL函数(转发)
查看>>
mysql分区表
查看>>
MySQL分层架构与运行机制详解
查看>>
mysql分库分表中间件简书_MySQL分库分表
查看>>