Đã đăng vào thg 5 25, 2017 9:37 SA 2 phút đọc Nested functionTrong Javascript, bạn có thể lồng 1 hàm bên trong 1 hàm khác. Tất cả các biến (variables) cũng như đối số (arguments ) từ hàm cha (outer function) đều được "kế thừa" từ hàm con (inner function). Nói cách khác, Inner function chứa Scope của outner function.Trong khi đó outer function không thể sử dụng được các biến (variables) cũng như đối số (arguments) của inner function . Code example
Cùng giải thích 1 chút nhé:Trong hàm outside (outner function) ta có định nghĩa 1 hàm inside() , hàm này làm nhiệm vụ đơn giản là trả về tổng của 2 số - 1 tham số được truyền vào từ outner function, 1 tham số được truyền vào từ chính inner function . Cuối cùng, hàm outside sẽ trả về 1 hàm return inside; Closures
Trong Javascript, một Closure sẽ chứa function và những biến mà được khai báo trong tầm vực của function như mình đã nói ở trên. Trong đoạn code ở trên, khi chúng ta khai báo inner function, Javascript sẽ tạo một Closure và cho function đó cũng như tất cả các biến mà function đó truy xuất vào. Vì thế khi chúng ta gọi function được trả về từ function ‘pet’ nó vẫn có thể truy xuất được dữ liệu của biến ‘name’. Trên đây, là 1 chút chia sẻ mà mình biết được về nested function cũng như closure trong Javascript, Rất mong nhận được sự góp ý của mọi người Nguồn tham khảo: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Functions https://developer.mozilla.org/en/docs/Web/JavaScript/Closures#Closure https://codeaholicguy.com/2015/12/31/javascript-closures/All rights reserved Right. The function you pass to getLocations() won't get called until the data is available, so returning "country" before it's been set isn't going to help you. The way you need to do this is to have the function that you pass to geocoder.getLocations() actually do whatever it is you wanted done with the returned values. Something like this:
If you might want to do something different every time you get the location, then pass the function as an additional parameter to reverseGeocode:
If this looks a little messy, then you could take a look at something like the Deferred feature in Dojo, which makes the chaining between functions a little clearer. |