我在函数中有一个局部表变量,还有一个子函数应该有一个同名的变量,同时仍然能够访问父变量。这应该是显而易见和直接的,但不幸的是,如果我在任何地方定义一个具有相同名称的局部变量,JavaScript 不允许我访问父变量:
var p = {alpha : 'beta'};
console.debug (p);
// [08:16:21.896] ({alpha:"beta"})
// Okay.
(function() {
console.debug (p);
// [08:16:21.896] ({alpha:"beta"})
// Right! JavaScript, you're so awesome!
})();
// One moment though, I think I still need the parent's table...
(function() {
var p = { 'p': p };
console.debug (p);
// [08:16:21.896] ({p:(void 0)})
// Wait, what?
})();
// Okay, maybe giving it the same name in the same statement confuses you?
(function() {
var parent_p = p;
var p = {};
console.debug (parent_p);
// [08:16:21.897] undefined
})();
// Give me back my variable! http://v.gd/jsWhyDoYouDoThis
那里发生了什么事?有没有办法解决这个问题?