Javascript 如何将“this”对象传递给使用协议apply的函数中调用的回调函数
如下所示的主函数,这将导致“setState”不是有效的属性异常Javascript 如何将“this”对象传递给使用协议apply的函数中调用的回调函数,javascript,callback,this,Javascript,Callback,This,如下所示的主函数,这将导致“setState”不是有效的属性异常 componentWillMount = function () { api.daysOfMonth(this, this.props.month, this.props.year, function (ds) { var days = []; ds.forEach(function (jsonDay) { var day = {date: jsonDay.date
componentWillMount = function () {
api.daysOfMonth(this, this.props.month, this.props.year, function (ds) {
var days = [];
ds.forEach(function (jsonDay) {
var day = {date: jsonDay.date, inRange: jsonDay.inRange};
days.push(day);
});
this.setState({ daysOfMonth: days });
});
下面是api.js的片段。
主函数调用Api.daysOfMonth…,Api.daysOfMonth将使用全局对象调用ajax方法并使用protocol apply调用回调函数,回调函数从主函数传入,如上脚本所示
apimpl=函数{
函数apimpl{}
apimpl.prototype.invoke=函数callerObj,回调,操作{
var参数=[];
对于var_i=3;_icomponentWillMount = function () {
api.daysOfMonth(this, this.props.month, this.props.year, function (ds) {
var days = [];
ds.forEach(function (jsonDay) {
var day = {date: jsonDay.date, inRange: jsonDay.inRange};
days.push(day);
});
this.setState({ daysOfMonth: days });
}.bind(this));
另见:
请注意,如果您编写es6,您可以使用arrow函数来完成相同的操作
componentWillMount = function () {
api.daysOfMonth(this, this.props.month, this.props.year, (ds) => {
var days = [];
ds.forEach(function (jsonDay) {
var day = {date: jsonDay.date, inRange: jsonDay.inRange};
days.push(day);
});
this.setState({ daysOfMonth: days });
});
简而言之,arrow函数中的这个范围是词法范围,这意味着它保证与定义arrow函数的地方相同
另请参见:您希望这是什么?星期一?是的,你的解决方案很好!我把bind放在了内部函数中,我应该把它放在我的主函数中。谢谢。