javascript 在一个函数调用之前调用其它方法

我想要实现这样一个效果:

function f = function(){
    console.log(1);
}
f.before(function(){
    console.log(2);
})
f(); //我想要这里输出为:2 1

请问before函数要怎么实现?


呼唤远方
浏览 914回答 1
1回答

一只甜甜圈

Function.prototype.before = function() {&nbsp; for (var i=0; i<arguments.length; i++) {&nbsp; &nbsp; if (typeof arguments[i] === 'function') {&nbsp; &nbsp; &nbsp; arguments[i]()&nbsp; &nbsp; }&nbsp; }&nbsp; this()}在chrome的控制台测试可以达到你想要的效果,,不过可能会有兼容性问题更新好像没什么意思,不过还是折腾了一下Function.prototype.before = function() {&nbsp; this.beforeArrFunc = []&nbsp; for (var i=0; i<arguments.length; i++) {&nbsp; &nbsp; if (typeof arguments[i] === 'function') {&nbsp; &nbsp; &nbsp; this.beforeArrFunc.push(arguments[i])&nbsp; &nbsp; }&nbsp; }}Function.prototype.execute = function() {&nbsp; for (var i=0; i<this.beforeArrFunc.length; i++) {&nbsp; &nbsp; this.beforeArrFunc[i]()&nbsp; }&nbsp; this()}var a = function() {&nbsp; console.log(1)}a.before(function() { console.log(2) })a.execute()这样的缺点是,具体调用时需要另一个实例方法来辅助好处就是也可以直接调用a(),这样不会调用到before function
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript