decrator

来源:2-2 decorator修饰器语法

荔枝小时

2018-07-26 15:42

function log(target) {

console.log(Object.getOwnPropertyDescriptor(target.prototype));  // undefined  这里打印 ??????

const desc = Object.getOwnPropertyDescriptor(target.prototype);

for (const key of Object.keys(desc)) {

if (key === 'constructor') {

continue;

}


const func = desc[key].value;


if ('function' === typeof func) {

Object.defineProperty(target.prototype, key, {

value(...args) {

console.log('before', key);

const ret = func.apply(this, args);

console.log('after', key);

return ret;

}

})

}

}

}


@log

class Numberic {

PI = 3.1415926;

add (...nums) {

return nums.reduce((p, n) => ( p + n ), 0)

}

}


new Numberic(1, 2);

写回答 关注

2回答

  • 高龙丶
    2019-01-10 20:56:39

    你好,我也遇到targer.prototype为undefined。这个问题怎么解决的?谢谢

  • 别秋景
    2018-08-26 17:31:50

    getOwnPropertyDescriptor 和 getOwnPropertyDescriptors 

mobx入门基础教程

mobx框架基础入门,使用mobx做状态管理

18819 学习 · 54 问题

查看课程