我尝试修改标准内置方法then
(请参见下文)会引发以下错误:
TypeError: Method Promise.prototype.then called on incompatible receiver undefined
at then (<anonymous>)
at Promise.then
实施(运行时:浏览器)
(function() {
console.log(this.Promise);
const oldThen = this.Promise.prototype.then;
this.Promise.prototype.then = function() {
console.log('modification');
return oldThen(arguments);
};
})()
Promise.resolve(1).then(fv => {
console.log(`Promise.resolve().then(..): `, fv);
});
有什么想法吗?
编辑:
通过箭头函数将this
绑定到全局对象似乎也不起作用:
(function() {
console.log(this.Promise);
const oldThen = this.Promise.prototype.then;
this.Promise.prototype.then = () => {
console.log('modification');
console.log(this.Promise); // this is now the global object
return oldThen(arguments[0]);
};
})()
Promise.resolve(1).then(fv => {
console.log(`Promise.resolve().then(..): `, fv);
});
答案 0 :(得分:1)
您需要使用正确的oldThen
来致电this
:
return oldThen.apply(this, arguments);
您还需要直接传递参数,而不是包装在数组中。