我寫了一個數組對象,然後通過數組wonna循環。我正在使用下劃線_.each函數來完成這項工作。突然,它發生意想不到的事情在我的代碼,考慮下面的代碼javascript沒有範圍函數參數
var _ = require('underscore');
var myArray = [ 'RE', 'FR', 'TZ', 'SD'];
var traverse = function (element, index, list) {
console.log(para1);
console.log(element);
}
var func1 = function (para1) {
_.each(myArray, traverse);
}
func1('test');
作爲輸出我有錯誤消息
Volumes/Develop/node_sample/scope.js:7
console.log(para1);
^
ReferenceError: para1 is not defined
at traverse (/Volumes/Develop/node_sample/scope.js:7:14)
at Array.forEach (native)
at Function._.each._.forEach (/Volumes/Develop/node_sample/node_modules/underscore/underscore.js:79:11)
at func1 (/Volumes/Develop/node_sample/scope.js:13:4)
at Object.<anonymous> (/Volumes/Develop/node_sample/scope.js:16:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
爲什麼遍歷功能不承認PARA1變量?我在func中執行_.each函數,並且在我看來應該包含範圍。
但如果我寫這樣的代碼,那麼作用域鏈正常工作
var _ = require('underscore');
var myArray = [ 'RE', 'FR', 'TZ', 'SD'];
var func1 = function (para1) {
_.each(myArray, function (element, index, list) {
console.log(para1);
console.log(element);
});
}
func1('test');