简体   繁体   English

可以回调函数访问父函数变量

[英]can callback functions access parent function variables

i have a load(callback) function which takes a callback function as parameter. 我有一个load(callback)函数,它将一个回调函数作为参数。 Can this callback function access variables present in its parent function ie load() 此回调函数可以访问其父函数中存在的变量,即load()

(function load(callback) 
{                
    return $.get("../somepage.aspx", {data:data},  function (response, status, xhr){   
        var x = 10; 
        if(typeof callback === 'function') { callback(); }
    }
})(done);

var done = function(){
  //do something with x here
  alert(x);
}

You cannot access x like you want because it is outside the scope of the done function. 您无法按自己的意愿访问x因为x超出了done函数的范围

You need to pass x to the callback: 您需要将x传递给回调:

(function load(callback) 
{                
    return $.get("../somepage.aspx", {data:data},  function (response, status, xhr){   
        var x = 10; 
        if(typeof callback === 'function') { callback(x); }
    }
})(done);

var done = function(x){
  //do something with x here
  alert(x);
}

I suspect this is what you want but to but I am taking a stab in the dark here seeing as how the code in the question has serious syntax problems (ie done is not a child of parent.) 怀疑这是您想要的,但是我在暗中摸索着看问题中的代码有严重的语法问题(即done不是父母的child )。

Nope, it can't because the callback's scope is totally outside the calling scope. 不,不是因为回调的作用域完全在调用作用域之外。 Pass x as a parameter in the callback. 在回调中传递x作为参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 函数可以访问在其自己的父函数中定义的变量吗? - Can functions access variables defined in its own parent function? 可以从ajax回调函数中查看父函数的变量吗? - can ajax callback function see variables from parent function? 从React中父组件的回调函数中的子组件访问变量,并在父组件中呈现返回的值 - Access variables from a child component in parent component's callback function in React and render the returned value in parent 回调函数访问闭包变量? - callback function access to closure variables? 我们可以使用在回调函数中定义的 javascript 变量,在它之外(回调函数)吗? - Can we use javascript variables which are defined in callback functions, outside of it(callback function)? 量角器:无法访问父函数中定义的闭包中的变量 - Protractor: Can not access variables in closure defined in parent function 解释为什么Javascript中的匿名函数可以访问外部函数中的变量? - Explain why anonymous functions in Javascript can access variables in the outer function? 嵌套函数可以使用在父函数中其他函数中设置了值的变量吗? (JavaScript) - Can nested functions use variables with values set in other functions within the parent function? (Javascript) 我可以访问函数变量吗? - Can I access functions variables? 为什么函数内部的变量对于在该函数内声明的回调函数是可见的? - Why are variables inside functions visible to callback functions declared inside that function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM