可以从ajax回调函数中查看父函数的变量吗?

[英]can ajax callback function see variables from parent function?


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

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.

我从javascript函数使用jQuery 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?

我想知道,ajax回调函数可以看到它的父函数的变量吗?这样做是不好的做法?

1 个解决方案

#1


10  

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.

这是JavaScript功能性的做事方式。它被称为闭包:函数从当前作用域和任何其他父作用域携带变量指针。因此,这不仅是一种良好的做法,而且这是您应该遵循的模式,而不是推动参数对象等。

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.

请注意,“this”引用是特殊的,它永远不会关闭(与任何其他引用相对),因此始终将全局对象指向匿名函数。

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.

实际上,开发人员需要一些时间来充分利用闭包功能 - 这是您刚才编写的基本示例。在更高级(而不仅仅是异步)方案中,闭包可以帮助您创建“即发即弃”行为,或者可以为您提供无法从客户端代码访问的“私有”变量(对库开发很有用)。 Closure还可以帮助您隔离代码,使其不会混淆全局范围。

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.

1)示例:如何使用闭包创建受保护变量。您可以访问两个可以访问“protectedVariable”的方法,但您无法自己访问它 - 因此可以保证控制。

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) isolation: the following code will not garbage the global scope even with "global" function definitions

2)隔离:即使使用“全局”函数定义,以下代码也不会垃圾全局范围

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

   var myNotGlobalFunction() {
      return protectedVariable;
   }

   return myNotGlobalFunction;
})();

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2012/10/19/167ce767eb56936518358d06fe1bff67.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号