为什么在使用 promise 构造时 angularjs throw 'Illegal invocation'?
Why angularjs throw 'Illegal invocation' when using promise construction?
我调用了一些 promise 函数:
return $http.post("anyCtrl").then(location.reload);
之后,我在 angular 中的浏览器控制台 'Illegal invocation' 中抛出了异常。
如果我调用:
return $http.post("anyCtrl").then(function(){location.reload()});
一切都很好。
我希望我的所有代码片段都能正常工作。
将 location.reload
作为参数传递与重新分配它或多或少相同。如果您重新分配一个对象的方法并且它未绑定,则该对象的 this
将成为它分配给的对象。例如:
const notlocation = {};
notlocation.reload = location.reload();
notlocation.reload(); // illegal invocation
您需要从 location
对象调用 reload
。有几种方法可以做到这一点。一种是像您所做的那样显式地在方法调用中加上括号:
$http.post("anyCtrl").then(() => location.reload());
另一种是使用.bind
并将其绑定到您要调用方法的对象:
$http.post("anyCtrl").then(location.reload.bind(location));
我调用了一些 promise 函数:
return $http.post("anyCtrl").then(location.reload);
之后,我在 angular 中的浏览器控制台 'Illegal invocation' 中抛出了异常。
如果我调用:
return $http.post("anyCtrl").then(function(){location.reload()});
一切都很好。
我希望我的所有代码片段都能正常工作。
将 location.reload
作为参数传递与重新分配它或多或少相同。如果您重新分配一个对象的方法并且它未绑定,则该对象的 this
将成为它分配给的对象。例如:
const notlocation = {};
notlocation.reload = location.reload();
notlocation.reload(); // illegal invocation
您需要从 location
对象调用 reload
。有几种方法可以做到这一点。一种是像您所做的那样显式地在方法调用中加上括号:
$http.post("anyCtrl").then(() => location.reload());
另一种是使用.bind
并将其绑定到您要调用方法的对象:
$http.post("anyCtrl").then(location.reload.bind(location));