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 am using jQuery ajax call from javascript function. I tried the above code and it works, but I don't know if it will cause any problems in the future.

I want to know if the ajax callback function can see the variables of this parent function? and is this a bad practice for this?

+4
source share
1 answer

This is a functional way to work with JavaScript. He called closure: functions transfer variable pointers from their current scope and from any other parent scope. Thus, this is not only good practice, but it is a template that you usually should follow, instead of clicking on parameter objects, etc.

Please note that the "this" link is special, it never closes (unlike any other links) and therefore always points the global object to anonymous functions.

In fact, it takes a developer some time to fully utilize the power of the closure function - this is the main example that you just wrote. In more complex (and not only asynchronous) scenarios, closing helps you create fire and forget behavior or can provide you with private variables that are not available from client code (useful for developing a library). Closing will also help you isolate your code so that it does not interfere in the global area.

1) Example: how to create protected variables with closure. You can use two methods that can access protected protected, but you cannot access it yourself, so 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): the following code will not destroy the global scope even with "global" function definitions

 var API = (function() { var protectedVariable = 0; var myNotGlobalFunction() { return protectedVariable; } return myNotGlobalFunction; })(); 
+10
source

Source: https://habr.com/ru/post/1440700/


All Articles