可以Ajax回调函数看到父函数的变量? [英] can ajax callback function see variables from parent function?

查看:344
本文介绍了可以Ajax回调函数看到父函数的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function validateHistoryId(input) {
    $.getJSON('request.php', {"action": "historyExists", "history_id" : input.value},
              function(data) {
                  console.log(input.value);
              }
    );
}

我使用的JavaScript函数jQuery的AJAX调用。我尝试了上面的code和它的作品,但我不知道它会导致在未来的任何问题。

i use jQuery ajax call from javascript function. I tried the above code and it works, but I don't know will it cause any problems in the future.

我想知道,可以Ajax回调函数看到的变量它的父功能?而且它是一个不好的做法,这样做呢?

I want to know, can ajax callback function see variables of it's parent function? and is it a bad practice to do so?

推荐答案

这是JavaScript功能的方式来做事。这就是所谓的闭包:功能传递变量的指针从目前的范围和任何其他父范围。 因此,这不仅是很好的做法,但是这是你通常应该遵循而不是围绕参数的对象,等推模式。

This is the JavaScript functional way to doing things. It's called closure: functions carry variable pointers from their current scope and from any other parent scope. So it's not only good practice, but this is the pattern you should normally follow instead of pushing around parameter objects, etc.

请注意到,这个的参考是特殊的,它永远不会闭包(相对于任何其它参考文献),并因此总是指向全局对象在匿名功能

Please notice that the "this" reference is special, it is never closured (as opposed to any other references) and thus always point the global object in anonymous functions.

其实开发人员需要一段时间才能完全采用封闭特征的力量 - 这是你刚才写了一个基本的例子。在更高级的(而不是仅仅异步)关闭的情况帮助你打造发射后不管的行为,或者可以为您提供私人的变量不是来自客户端的code访问(用于图书馆的发展)。关闭还可以帮助你找出你的code,这样才不会乱用全局范围。

In fact a developer needs some time to fully employ the power of the closure feature - this is a basic example you just written. In more advanced (and not solely async) scenarios closure helps you to create "fire and forget" behavior, or can provide you with "private" variables that are not accessible from client code (useful for library development). Closure also help you isolate your code so that it will not mess with the global scope.

1)例如:如何建立与关闭受保护的变量。你能够acccess可以访问protectedVariable,但你不能够访问它自己的两种方法 - 这样的控制是有保障

1) Example: how to create protected variables with closures. You are able to acccess two methods that can access "protectedVariable" but you are not able to access it yourself - so the control is guaranteed.

function protectedScope(initData) {
  var protectedVariable = initData;

  return {
    getter: function()  { return protectedVariable; }
    setter: function(v) { protectedVariable = v; }
  }
}

var methods = protectedScope(10);

console.log(methods.getter());

2)隔离:以下code不会垃圾甚至与全球范围内的全球的功能定义

2) isolation: the following code will not garbage the global scope even with "global" function definitions

var API = (function() {
   var protectedVariable = 0;

   var myNotGlobalFunction() {
      return protectedVariable;
   }

   return myNotGlobalFunction;
})();

这篇关于可以Ajax回调函数看到父函数的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆