Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript&;jQuery:调用内部函数_Javascript_Jquery - Fatal编程技术网

JavaScript&;jQuery:调用内部函数

JavaScript&;jQuery:调用内部函数,javascript,jquery,Javascript,Jquery,我用JavaScript和jQuery编写了以下代码,其中包含一个集成的ajax请求。 问题:为什么可以调用内部函数success1(),但不能调用this.success2()?对这个问题有什么解决方案吗 function myfuntion() { this.url = "www.example.com/ajax.php"; var success1 = function (data) { alert("SUCCESS1"); } this.s

我用JavaScript和jQuery编写了以下代码,其中包含一个集成的ajax请求。 问题:为什么可以调用内部函数
success1()
,但不能调用
this.success2()
?对这个问题有什么解决方案吗

function myfuntion() {
    this.url = "www.example.com/ajax.php";
    var success1 = function (data) {
        alert("SUCCESS1");
    }
    this.success2 = function (data) {
        alert("SUCCESS2");
    }
    this.send = function () {
        $.ajax({
            type: "POST",
            url: this.url,
            dataType: "html"
        }).done(function (data) {
            success1(data);
            this.success2(data);
        });
    }
}
var test = new myfunction().send();

正如其他人所评论的,send函数中的
this
的上下文已更改,因此您的
success2
函数没有调用。您应该将
myFunction
上下文保存在变量中,并使用该变量引用
上下文

试试这个:

function myfuntion() {
    var self = this;                // taking the current context in a variable.

    self.url = "www.example.com/ajax.php";
    var success1 = function (data) {
        alert("SUCCESS1");
    }
    self.success2 = function (data) {
        alert("SUCCESS2");
    }
    self.send = function () {
        $.ajax({
            type: "POST",
            url: self.url,
            dataType: "html"
        }).done(function (data) {
            success1(data);
            self.success2(data);
        });
    }
}

因为在回调中,
这个
引用了另一个对象。您可能想看看公认的答案,以获得对JavaScript“this”的极好解释