您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

JavaScript中函数Decorator实例详解

2024/5/3 12:10:29发布38次查看
这篇文章主要介绍了javascript装饰器函数(decorator),结合实例形式分析了javascript装饰器函数(decorator)的功能、实现与使用方法,需要的朋友可以参考下
本文实例讲述了javascript装饰器函数(decorator)。分享给大家供大家参考,具体如下:
装饰器函数(decorator)用于给对象在运行期间动态的增加某个功能,职责等。相较通过继承的方式来扩充对象的功能,装饰器显得更加灵活,首先,我们可以动态给对象选定某个装饰器,而不用hardcore继承对象来实现某个功能点。其次:继承的方式可能会导致子类繁多,仅仅为了增加某一个单一的功能点,显得有些多余了。
下面给出几个常用的装饰器函数示例,相关代码请查看github。
1 动态添加onload监听函数
function addloadevent(fn) { var oldevent = window.onload; if(typeof window.onload != 'function') { window.onload = fn; }else { window.onload = function() { oldevent(); fn(); }; } } function fn1() { console.log('onloadfunc 1'); } function fn2() { console.log('onloadfunc 2'); } function fn3() { console.log('onloadfunc 3'); } addloadevent(fn1); addloadevent(fn2); addloadevent(fn3);
2 前置执行函数和后置执行函数
function.prototype.before = function(beforfunc) { var self = this; var outerargs = array.prototype.slice.call(arguments, 1); return function() { var innerargs = array.prototype.slice.call(arguments); beforfunc.apply(this, innerargs); self.apply(this, outerargs); }; }; function.prototype.after = function(afterfunc) { var self = this; var outerargs = array.prototype.slice.call(arguments, 1); return function() { var innerargs = array.prototype.slice.call(arguments); self.apply(this, outerargs); afterfunc.apply(this, innerargs); }; }; var func = function(name){ console.log('i am ' + name); }; var beforefunc = function(age){ console.log('i am ' + age + ' years old'); }; var afterfunc = function(gender){ console.log('i am a ' + gender); }; var beforefunc = func.before(beforefunc, 'andy'); var afterfunc = func.after(afterfunc, 'andy'); beforefunc('12'); afterfunc('boy');
执行结果,控制台打印如下:
i am 12 years old i am andy i am andy i am a boy
3 函数执行时间计算
function log(func){ return function(...args){ const start = date.now(); let result = func(...args); const used = date.now() - start; console.log(`call ${func.name} (${args}) used ${used} ms.`); return result; }; } function calculate(times){ let sum = 0; let i = 1; while(i < times){ sum += i; i++; } return sum; } runcalculate = log(calculate); let result = runcalculate(100000); console.log(result);
注:这里我使用了es2015(es6)语法,如果你感兴趣可以查看前面关于es6的相关内容。
当然,装饰器函数不仅仅这些用法。天猫使用的nodejs框架koa就基于装饰器函数及es2015的generator。希望这篇文章能起到抛砖引玉的作用,使你编写更优雅的js代码。
以上就是javascript中函数decorator实例详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product