JS "动态织入"返回值的问题

Function.prototype.before = function(beforefn) {
        var _self = this;
        return function() {
            beforefn.apply(this, arguments);
            return _self.apply(this, arguments);

        }
    }

    Function.prototype.after = function(afterfn) {
        var _self = this;
        return function() {
            **var ret = _self.apply(this, arguments);** //这一块不是应该输出2么   
            afterfn.apply(this, arguments);
            return ret;
        }
    }

    var func = function() {
        console.log(2);
    }

    func = func.before(function() {
        console.log(1);
    }).after(function() {
        console.log(3);
    })

    func();

程序输出结果是 1, 2 ,3 . 但为啥不是 12 23, 因为Function.prototype.after里面第一步就是 _self.apply() ?

阅读 2.6k
1 个回答

稍微改一下,看你看得懂不

javascriptvar func = function() {
    console.log(2);
}

func = func.before(function() {
    console.log(1);
});

func();

func = func.after(function() {
    console.log(3);
});

func();

输出

1
2
1
2
3
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题