纯Javascript:覆盖功能

时间:2016-09-30 10:11:53

标签: javascript

我想覆盖一些函数(用于记录一些信息)

我正在尝试做类似的事情:

function universe() {
  return 42;
}

universe = universe.override(function(){
  console.log("Calling universe");
  return this.$super();
});

完整样本:

Function.prototype.override = function (fn) {
    var $super = this;
    var f = function overrided() {
        var context = this || $super || {};
        context.$super = $super;
        return fn.apply(context, arguments);
    };
    f.$super = $super;
    return f;
};

Function.prototype.unoverride = function () {
    if (this.$super) {
        return this.$super;
    }
    return this;
};

function universe() {
	return 42;
}

function mulBy10() {
	console.warn("calling overrided function");
  return this.$super() * 10;
}

console.log("---------");
console.log("original:", universe());

universe = universe.override(mulBy10);

console.log("new one:", universe());

universe = universe.unoverride();
console.log("reverted:", universe());

console.log("--With Object");

var MyObject = function() {
	this.value = 42;
}
MyObject.prototype = {
	constructor: MyObject,
  getValue: function() {
	  return this.value;
  }
};

var o1 = new MyObject();
console.log("MyObject original:", o1.getValue());

o1.getValue = o1.getValue.override(mulBy10);
console.log("MyObject new one:", o1.getValue());

o1.getValue  = o1.getValue.unoverride();
console.log("MyObject reverted:", o1.getValue());


console.log("--With Object prototype");
o2 = new MyObject();

MyObject.prototype.getValue = MyObject.prototype.getValue.override(mulBy10);
console.log("MyObject.proto new one:", o2.getValue());

MyObject.prototype.getValue = MyObject.prototype.getValue.unoverride();
console.log("MyObject.proto reverted:", o2.getValue());

console.log("--With recursive");

function recur(it, max) {
	console.log("it:", it, "max:", max);
  if( it >= max ) {
  	console.log("finished");
    return;
  }
  recur(it + 1, max);
}

recur = recur.override(function(it, max){
	console.warn("Overrided recur");
  return this.$super(it, max);
});

recur(0, 4);

这与函数,对象函数一起工作正常。 但是当我试图覆盖CasperJs“require”函数时,它不起作用。 我做了:

require = require.override(function(file){
  console.log("require(" + file + ")");
  return this.$super(file);
});

所以我想知道,在这种情况下,override功能不起作用?

我是否错过了CasperJS require函数中的某些内容?

0 个答案:

没有答案