Monkey-patch Promise构造函数

时间:2017-04-20 16:09:11

标签: javascript node.js

就像练习一样,我尝试对Promise构造函数进行猴子修补,如下所示:

const pconstructor = global.Promise;
global.Promise = function (fn1) {
  this.foo = 'bar';
  pconstructor.call(this,fn1);
};

global.Promise.resolve = pconstructor.resolve;

然而,当我打电话

时,我收到错误
Promise.resolve();

=>

TypeError: [object Object] is not a promise

任何人都知道如何正确修补这样的构造函数吗?

1 个答案:

答案 0 :(得分:3)

我建议只编写Promise的子类:



const global = window; // (in browser...)


const OldPromise = global.Promise; 
global.Promise = class Promise extends OldPromise {
  constructor(executor) {
    // do whatever you want here, but must call super()
    console.log('hello, promise');

    super(executor); // call native Promise constructor
  }
};

Promise.resolve(); // prints: "hello, promise"




当尝试对这样的类进行猴子修补时,这会处理幕后的所有细节。