Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/387.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/2/jquery/79.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变量作用域_Javascript_Jquery - Fatal编程技术网

回调中的javascript变量作用域

回调中的javascript变量作用域,javascript,jquery,Javascript,Jquery,我很好奇这怎么写得更好: function Klass(variable) { this.variable = variable; this.callAjax = function() { $.get('/url', { }, function(json) { console.log(variable); //! <-- shows undefined }, "json"); } } 函数Klass(变量)

我很好奇这怎么写得更好:

function Klass(variable) {
    this.variable = variable;

    this.callAjax = function() {
        $.get('/url', { }, function(json) {
            console.log(variable); //! <-- shows undefined
        }, "json");
    }
}
函数Klass(变量){
this.variable=变量;
this.callAjax=function(){
$.get('/url',{},函数(json){

console.log(变量);/!就是这样

function(json){console.log(_variable);} 
用“_变量”形成一个闭包。 “_变量”永远保留原始值

如果以后需要更新“变量”,并且希望更新“变量” 你定义

var self = this; 
并调用self.variable来获取它

这样,每次执行回调时,您都会得到更新的“变量”

完整代码:

function Klass(variable) {
    var self = this;
    this.variable = variable;
    this.callAjax = function() {
        $.get('/url', { }, function(json) {
            console.log(self.variable);
        }, "json");
    }
}

就是这样

function(json){console.log(_variable);} 
用“_变量”形成一个闭包。 “_变量”永远保留原始值

如果以后需要更新“变量”,并且希望更新“变量” 你定义

var self = this; 
并调用self.variable来获取它

这样,每次执行回调时,您都会得到更新的“变量”

完整代码:

function Klass(variable) {
    var self = this;
    this.variable = variable;
    this.callAjax = function() {
        $.get('/url', { }, function(json) {
            console.log(self.variable);
        }, "json");
    }
}

$.get(…function(){…}.bind(this))
我不明白为什么
控制台.log(variable);
应该显示
未定义的
变量
应该引用构造函数参数。是否将
未定义的
传递给构造函数并稍后设置
此.variable
$.get(…function(){…}.bind(this))
我不明白为什么
console.log(变量)
应该显示
未定义的
变量
应该引用构造函数参数。您是否将
未定义的
传递给构造函数并在以后设置
此.variable
?您也可以在构造函数中声明
self
,因为
callAjax
是一个特权方法(在构造函数中声明)。您的方法更好,因为它也适用于原型方法。您是对的,我想知道为什么问题中的第一个案例不起作用。它应该起作用,只是变量不会改变。您也可以在构造函数中声明
self
,因为
callAjax
是一个特权方法(在构造函数中声明).你的方法更好,因为它在原型方法中也有效。你是对的,我想知道为什么问题中的第一种情况不起作用。它应该起作用,只是变量不会改变。