我有以下js文件:
function RequestHandler(marker) {
this.marker = marker;
this.getDate = function () {
var currentdate = new Date();
var datetime = currentdate.getDate() + "/" + (currentdate.getMonth() + 1)
+ "/" + currentdate.getFullYear() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
return datetime;
}
this.registerEventHandlers = function () {
$('[data-send-event]').on('click', function () {
requestData = {
Timestamp: this.getDate(),
EventType: 0,
Latitude: marker.getPosition().lat(),
Longitude: marker.getPosition().lng()
}
});
}
当js触发$('[data-send-event]').on('click')
时,它给我一个错误,即找不到this.getDate()
。有人可以帮我吗?
答案 0 :(得分:1)
该函数内部的范围不正确。您可以做几件事:
将范围绑定到函数
this.registerEventHandlers = function () {
$('[data-send-event]').on('click', (function () {
requestData = {
Timestamp: this.getDate(),
EventType: 0,
Latitude: marker.getPosition().lat(),
Longitude: marker.getPosition().lng()
}
}).bind(this));
}
将范围保存在变量中以对其进行访问
this.registerEventHandlers = function () {
var that = this;
$('[data-send-event]').on('click', function () {
requestData = {
Timestamp: that.getDate(),
EventType: 0,
Latitude: marker.getPosition().lat(),
Longitude: marker.getPosition().lng()
}
});
}
使用箭头功能:
this.registerEventHandlers = function () {
$('[data-send-event]').on('click', () => {
requestData = {
Timestamp: this.getDate(),
EventType: 0,
Latitude: marker.getPosition().lat(),
Longitude: marker.getPosition().lng()
}
});
}