【问题标题】:Javascript: Scope issues in object [duplicate]Javascript:对象中的范围问题[重复]
【发布时间】:2018-07-20 00:23:42
【问题描述】:

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

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 中 this 的范围有关:

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?

【问题讨论】:

    标签: javascript jquery scope prototype


    【解决方案1】:

    改变 $('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 元素

    【讨论】:

    • 如果我绑定到 'this',我可以访问 errorsArray 但我无法访问我正在处理的当前字段,这意味着 var field = '#' + $(this)[0 ].id 不起作用
    • @MrCujo:啊,这是 jquery api 的一个非常烦人的部分。我会更新我的答案(tl;博士你应该传入两个参数)
    • @MrCujo:更新
    • 确实有效。我非常感谢你的时间。谢谢!只是想知道,是否有可能通过闭包来保护范围来解决这个问题?
    猜你喜欢
    • 2012-05-29
    • 2013-04-01
    • 2022-12-17
    • 2016-08-28
    • 1970-01-01
    • 2012-12-27
    • 2021-12-04
    • 2013-06-05
    • 1970-01-01
    相关资源
    最近更新 更多