Javascript can';t将变量设置为外部函数

Javascript can';t将变量设置为外部函数,javascript,variables,call,Javascript,Variables,Call,我似乎无法在ajax函数中设置this.chkOK。我不知道该怎么做,所以我想也许可以调用validateFields.call(这个)应该可以解决我的问题,但我发现事实并非如此。所以我有点迷失了下一步该做什么。我不想将其设置为全局变量,除非我必须这样做。我正在尝试设置此值。chkOK=true function validateFields() { this.chkOK = null; this.username = function() { if(FS.gID('username

我似乎无法在ajax函数中设置this.chkOK。我不知道该怎么做,所以我想也许可以调用validateFields.call(这个)应该可以解决我的问题,但我发现事实并非如此。所以我有点迷失了下一步该做什么。我不想将其设置为全局变量,除非我必须这样做。我正在尝试设置此值。chkOK=true

function validateFields() {

this.chkOK = null;

this.username = function() {
    if(FS.gID('username').value.length >= 2) {

        var user = FS.gID('username').value;


        //Make sure that the username doesn't already exist
        FS.ajax('/server/chkUser.php?user='+user,'GET',function(){
            validateFields.call(this);
            if(xmlText == 0) {

                    this.chkOK = true;
                alert("This user doesn't exist.");


            }
            else if(xmlText == 1) {
                alert("Theres already a user with this username");
                this.chkOK = false;

            }
        });

    }
    else {
        alert("empty");
        this.chkOK = false;
    }
alert(this.chkOK);

}
 }

这是因为FS.ajax中的内容与您打算使用的内容不同
this
在FS.ajax中是指FS的这一部分

您可以将其分配到另一个变量中,并在FS.ajax中使用它。比如说,

注意:除非您知道将
this.chkOk
放在函数中的原因(例如,
调用调用的预期验证字段
应用
是全局对象(您不想)或
未定义
处于严格模式,这将导致代码失败


在您的示例中,
this
的值不是声明它的函数,就像您在代码中假设的那样


如果只使用
var chkOK=null
而不是
this.chkOK=null它应该开始工作了

你应该格式化/缩进你的代码,无论是为了你自己还是为了其他人的利益。在
this.chkOK=null顶部的语句?老实说,我不知道,因为我没有看到完整的代码。。。我希望该函数存在于一个对象中,这就是他将其放入代码中的原因。在函数中对
this
的裸引用,除非该函数通过
call
apply
调用,否则将是全局对象,或在严格模式下
未定义的
,这将导致他的代码失败,如果他想让它成为函数的局部变量,那么你应该指出这一点。非常感谢你的澄清。
function validateFields() {

    this.chkOK = null;

    // ** assign this to that. So you can reference it inside FS.ajax **
    var that = this;

    this.username = function() {
        if(FS.gID('username').value.length >= 2) {
            var user = FS.gID('username').value;

            //Make sure that the username doesn't already exist
            FS.ajax('/server/chkUser.php?user='+user,'GET',function(){
                validateFields.call(this);
                if(xmlText == 0) {
                    that.chkOK = true; // use `that` instead of `this`. 
                    alert("This user doesn't exist.");
                } else if(xmlText == 1) {
                    alert("Theres already a user with this username");
                    that.chkOK = false; // use `that` instead of `this`
                }
            });
        } else {
            alert("empty");
            this.chkOK = false;
        }

        alert(this.chkOK);
    }
}