gpt4 book ai didi

JavaScript Promise 和 this 关键字

转载 作者:行者123 更新时间:2023-11-29 19:46:03 25 4
gpt4 key购买 nike

给定以下 JS,如何设置 PlateCheck 对象的 message 属性?

var plateCheck = {
plateNumber: '',
message: '',
alertClass: '',
checkPlate: function (plateNumber) {
PlateCheckService.checkPlate(plateNumber).then(function (response) {
var data = response.data;

if (data.VehicleAtl !== null) {
this.message = "Hot!";
this.alertClass = 'alert-danger';
} else {
this.message = "Plate #" + data.PlateNumber + " is clean.";
this.alertClass = 'alert-success';
}
});
}
};

编辑

PlateCheckService.checkPlate(plateNumber) 返回一个 promise ...

最佳答案

这可能只是一个范围问题,但通过调用 plateCheck.checkPlate(fooPlateNumber) 返回相同的对象也许可以解决问题。

var plateCheck = {
plateNumber: '',
message: '',
alertClass: '',
checkPlate: function (plateNumber) {
var me = this;
PlateCheckService.checkPlate(plateNumber).then(function (response) {
var data = response.data;
me.plateNumber = plateNumber;
if (data.VehicleAtl !== null) {
me.message = "Hot!";
me.alertClass = 'alert-danger';
} else {
me.message = "Plate #" + data.PlateNumber + " is clean.";
me.alertClass = 'alert-success';
}
});
}
};

但也许您可以提取服务函数,返回一个 plateCheck 对象。

function checkPlate(plateNumber) {
var plateCheck = {};
plateCheck.plateNumber = plateNumber;
PlateCheckService.checkPlate(plateNumber).then(function (response) {
var data = response.data;
if (data.VehicleAtl !== null) {
plateCheck.message = "Hot!";
plateCheck.alertClass = 'alert-danger';
} else {
plateCheck.message = "Plate #" + data.PlateNumber + " is clean.";
plateCheck.alertClass = 'alert-success';
}
});
return plateCheck;
}

关于JavaScript Promise 和 this 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19622661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com