【发布时间】:2018-07-20 15:53:03
【问题描述】:
我尝试修改标准内置方法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);
});
【问题讨论】:
-
看起来您在任何时候都没有将参数传递给新函数参数
-
@stmfunk 知道了,我可以使用 apply 来传递参数。有没有一种休息、传播或解构的方法,我们可以将所有参数传递给另一个函数(不应用)?
标签: javascript browser promise typeerror