分析一段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);			
			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();

  这里所谓的 JS 动态织入 算是一种模式。

  代码最终执行的返回结果是 打印出

  1

  2

  3

  


 之前自己一直理解不了 打印出 1 2 3的原因,总以为应该是 1 2 2 3,  2 3 便是 after() 中打印出来的值。

但其实当 连续调用 func.before().after() 的时候,其次 after 中的  var _self = this; 其实表示的是 before() 的返回值,根据代码,返回值 是

return function() {
            beforefn.apply(this, arguments);
            return _self.apply(this, arguments);
        }

带入到 整理当中 最终执行的便是

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

(function() {
            beforefn.apply(this, arguments);  //打印出 1
            return _self.apply(this, arguments);   //打印出2
        })();
(function() {
		console.log(3);   // 打印出3
	});

 

  所以最终的结果也就是 123, 并且之所以能够 链式调用 是因为 before() 返回值也是 一个函数,所以也存在 after() 方法。

原文地址:https://www.cnblogs.com/beyond1990/p/4681541.html