This question already has answers here:
How to access the correct `this` inside a callback?
                            
                                (11个答案)
                            
                    
                2年前关闭。
        

    

我无法从函数访问某些变量。这是我得到的:

var PTP = function (properties) {
    this.errorsArray = []
}


PTP.prototype.initHTMLItems = function () {
    $('input[data-widget-type="date"]').each(this.dateValidation)
}


PTP.prototype.dateValidation = function() {
    var field = '#' + $(this)[0].id
    var that = this
    $(field).focusout(function(){
        var valid = form_validate_date($(field).val())
        var label = $('#date').siblings('label').children('.label-text').text()

        if (!valid) {
            that.errorsArray.push({
                'field': field,
                'fieldType': 'date',
                'errorMessage': 'Incorrect data' + (label !== undefined ? ' for ' + label : "")
            })
        }
    })
}


问题是我无法访问errorsArray。

我还尝试将回调函数作为参数传递给dateValidation:

PTP.prototype.addError = function(errorObj) {
    this.errorsArray.push(errorObj)
}


尝试过这种方式:

PTP.prototype.initHTMLItems = function () {
    $('input[data-widget-type="date"]').each(this.dateValidation(this.addError))
}


也是这样:

PTP.prototype.initHTMLItems = function () {
    $('input[data-widget-type="date"]').each(this.dateValidation.bind(this.addError))
}


但这与dateValidation中的范围搞砸了:

PTP.prototype.dateValidation = function(callback) {
    var field = '#' + $(this)[0].id
    var that = this
    $(field).focusout(function(){
        var valid = form_validate_date($(field).val())
        var label = $('#date').siblings('label').children('.label-text').text()

        if (!valid) {
            callback({
                'field': field,
                'fieldType': 'date',
                'errorMessage': 'Incorrect data' + (label !== undefined ? ' for ' + label : "")
            })
        }
    })
}


我怎样才能访问errorsArray?

最佳答案

更改
$('input[data-widget-type="date"]').each(this.dateValidation)



$('input[data-widget-type="date"]').each(function(index, element) {
  this.dateValidation(element);
}.bind(this));


然后更改PTP.prototype.dateValidation = function(callback) {

PTP.prototype.dateValidation = function(element) {
现在,在dateValidation中,this是您的PTP对象,而element是来自每个循环的jquery元素

10-06 00:03