javascript - 高阶函数实现 AOP 问题

查看:62
本文介绍了javascript - 高阶函数实现 AOP 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

书中有一段这样的代码

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);
    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();

我理解的执行过程是这样的

Function.prototype.before = function(beforefn) {
  var __self = this;
  return function() {
    beforefn.apply(this, arguments);//console.log(1)
    return __self.apply(this, arguments);//console.log(2)
  }
}

Function.prototype.after = function(afterfn) {
  var __self = this;
  return function() {
    var ret = __self.apply(this, arguments);//console.log(2)
    afterfn.apply(this, arguments);//console.log(3)
    return ret;
  }
}

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

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

func();
// 所以输出应该为1 2 2 3

实际输出是这样的

所以我不明白的是为什么只输出了一个2

__self.apply(this, arguments)

这一句应该是执行了2次才对

解决方案

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

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

此时  func  为    beforefn.apply(this, arguments);//console.log(1)
                 return __self.apply(this, arguments);//console.log(2)



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

此时func 为     __self.apply(this, arguments);  
               重点来了! 这里的self也就是this 指向的是上方的 第一个func, 也就是 console出 1 和 2 的函数
               afterfn.apply(this, arguments);//console.log(3)

最终的func是最后return出来的函数,只会执行一次哦。

这篇关于javascript - 高阶函数实现 AOP 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆