用AOP装饰函数

72 阅读1分钟
<button id="button">hhh</button>
    var _getElementById = document.getElementById;
    document.getElementById = function(){
        alert (1);
        return _getElementById.apply( document, arguments );
    }
    var button = document.getElementById( 'button' );
    console.log(button)

升级上面的js


    Function.prototype.before = function(beforeFn) {
        const _self = this
        return function() {
            beforeFn.apply(this, arguments)
            return _self.apply(this, arguments)
        }
    }
    Function.prototype.after = function(afterFn) {
        const _self = this
        return function() {
            const res = _self.apply(this, arguments)
            afterFn.apply(this, arguments)
            return res
        }
    }
    document.getElementById = document.getElementById.before(function() {
        alert('hahahhaha')
    })
    var button = document.getElementById( 'button' );
    console.log(button)
    
    
    // window.onload = function(){
    //     alert (1);
    // }
    // window.onload = ( window.onload || function(){} ).after(function(){
    //     alert (2);
    // }).after(function(){
    //     alert (3);
    // }).after(function(){
    //     alert (4);
    // })

如果不喜欢上述污染原型的方法,则使用下面的js


    var before = function( fn, beforefn ){
        return function(){
            beforefn.apply( this, arguments );
            return fn.apply( this, arguments );
        }
    }
    var a = before(
        function(){alert ('c')},
        function(){alert ('b')}
    );
    a = before( a, function(){alert ('a');} );
    a()