2015-07-21 71 views
0

这是一个简单的脚本,它将记录Photoshop文件中的文本内容。JavaScript行为范围

var numOfLayers = app.activeDocument.layers.length; 
var resultStr = ""; 

doAllLayers(); 
alert(resultStr); 

function addToString(alayer) 
{ 
    if (alayer.kind == "LayerKind.TEXT") 
    { 
    var c = alayer.textItem.contents; 
    resultStr += c; 
    } 
} 

// main loop 
function doAllLayers() 
{ 
    for (var i = numOfLayers -1; i >= 0; i--) 
    { 
     var thisLayer = app.activeDocument.layers[i]; 
     addToString(thisLayer); 
    } 
} 

它工作正常,但我真的应该传递一个字符串到函数添加到自身,但它的工作原理。 JavaScript的范围如何实现?声明的局部变量仍然被函数访问,还是我错过的另一个技巧?

+0

有什么问题,代码看起来很好。 – atinder

+0

我不确定我是否正确理解,但是您不会在这里传递任何字符串,thisLayer是您传递的对象。 – abs

+0

@atinder - 我只需要更好地理解JavaScript中的范围 –

回答

1

下面是变量范围的一些基本规则在JavaScript:

  • 如果与var关键字定义,变量是函数作用域。也就是说,该变量的范围是最接近的包含函数,或者如果没有包含函数,则该范围包含在全局上下文中。 实施例:

// globally-scoped variable (no containing function) 
var foo = 'bar'; 

function test() { 
    // function-scoped variable 
    var foo2 = 'bar2'; 

    if (true) { 
     // still function-scoped variable, regardless of the if-block 
     var foo3 = 'bar3'; 
    } 

    // see? 
    console.log(foo3); // --> 'bar3' 
} 
  • 如果与关键字let(ES6 +)定义,则变量是块范围的(此行为更类似于大多数其他C家族语法语言)。例如:

// error: top level "let" declarations aren't allowed 
let foo = 'bar'; 

function test() { 
    // block-scoped variable (function are blocks, too) 
    let foo2 = 'bar2'; 

    if (true) { 
     // block-scoped variable (notice the difference 
     // from the previous example?) 
     let foo3 = 'bar3'; 
    } 

    // uh oh? 
    console.log(foo3); // --> ReferenceError: foo3 is not defined 
} 
  • 如果既不与varlet关键字(例如,foo = bar)中所定义,则变量的作用域全局上下文。例如:

// globally-scoped variable 
foo = 'bar'; 

function test() { 
    // also globally-scoped variable (no var or let declaration) 
    foo2 = 'bar2'; 

    if (true) { 
     // still a globally-scoped variable 
     foo3 = 'bar3'; 
    } 
} 

test(); 
console.log(foo, foo2, foo3); // 'bar', 'bar2', 'bar3' 

在所有这些情况下,函数的变量的范围内定义仍可以访问变量本身(技术上讲你创建一个封闭,作为numOfLayers和​​变量词法范围你的addToStringdoAllLayers函数)。

请注意,范围规则在技术上比这更细微一些,但是您最好在此处阅读更深入的文章。

0

您已定义var resultStr = "";外部函数,它是一个全局变量。您可以访问addToString()内的全局变量并开始连接。请注意,在该方法内,您还没有声明var resultStr = "";,否则它将是该方法的局部变量。