JavaScript/jQuery的范围 [英] Scope in JavaScript / jQuery

查看:109
本文介绍了JavaScript/jQuery的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我显然已经写了太多的CoffeeScript,因为现在我意识到我对纯JS的作用域甚至还没有基本的了解.

I've clearly been writing too much CoffeeScript, as I am now realizing I do not have even a basic understanding of scope in pure JS.

玩了一段时间之后,我无法解决以下问题-

After playing for a while, I cannot figure out the problem with the following--

$(document).ready(function() {
    var myUrl = "http://notimportant.com/"
    var photos = getPhotos(myUrl);
    console.log(photos);                        //undefined
});

function getPhotos(url) {
    var a;
    $.get(url, function(data) {
        a = data["photoset"]["photo"];
        console.log(a);                        //my object
    });
    return a;
}

如果我将console.log(a)语句放在'var a = data ["photoset"] ["photo"];它表明它正确发出了我正在寻找的GET请求.但是我发现无法将该对象传递回我想要操作的主要代码块.

If I put a console.log(a) statement on the line right below 'var a = data["photoset"]["photo"];' it shows that it properly makes the GET request I'm looking for. But I'm finding it impossible to pass that object back to my main block of code, where I want to manipulate it.

谢谢.

推荐答案

未定义photos的原因不是因为作用域.这是因为$.get是异步执行的. $.get()返回jqXHR对象而不是HTTP响应.

The reason photos is undefined is not because of scopes. Its because $.get is executed asynchronously. $.get() returns jqXHR object instead of an HTTP response.

onSuccess回调应传递给getPhotos(),以使其正常工作.或者,可以使用when().then()构造.

onSuccess callback should be passed to getPhotos() in order to make it work correctly. Alternatively when().then() construct could be used.

$(document).ready(function() {
    var myUrl = "http://example.com/";
    getPhotos(myUrl, renderCatPhotos);    
});

function getPhotos(url, onSuccess) {
    $.get(url, onSuccess);
}

function renderCatPhotos(data) {
    var a = data.photoset.photo;
    console.log(a);  // a is always available
}

注意:您甚至可能不需要getPhotos功能.您可以直接在$(document).ready() 中使用$.get(url, onSuccess);.

note: you might not even need getPhotos function. You can simply $.get(url, onSuccess); in $(document).ready() instead.

这篇关于JavaScript/jQuery的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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