Mic*_*hat 0 javascript jquery scope
我一直在JavaScript中探索范围.消息来源指出,范围是以函数分隔的,而不是像大多数语言那样以块分隔的方式.
我在我正在写的一些代码中放了一些显示代码,因为我的一些函数 - 函数内部不清楚(对我而言),我想看看范围如何适用于这些.
令人惊讶的是,在$ .getJSON函数中的$ .each函数中,if(){}子句显然被视为一个函数.我本以为是一个街区.
function displayInfo(nKey) {
if(!nKey) var nKey = 0;
var objFilm = {};
var imgRef;
//iterate through all object properties; display their attributes
// Object.keys() returns an array of all property names
// for most entries, the object is ...film; check first for array of multiple films
jqxhr = $.getJSON('dbMovies.json', function(data) {
var xx = "xx";
$.each(data.disc, function(i, xdata) {
if(xdata.key == nKey) {
objFilm = xdata.film;
var yy = "yy";
imgRef = xdata.img;
return false;
}
console.log("in jqxhr, xx: " + typeof xx); //this shows
console.log("in jqxhr, yy: " + typeof yy); //this does NOT
}); // $.each
})
.done(function() {...}
Run Code Online (Sandbox Code Playgroud)
如果if(){}是一个函数,那么什么是块?
你return false在if中有一个内部,因此只有if条件不为真并且if控制的块没有运行时才会达到这两个日志语句的唯一时间.如果块没有运行,则yy没有分配值.它在范围内,但未初始化.