отсюда
There is a distinction between the function name and the variable the function is assigned to:
- The function name cannot be changed, while the variable the function is assigned to can be reassigned.
- The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:
var y = function x() {};
alert(x); // throws an error
The function name also appears when the function is serialized via Function's toString method.
Касательно вашего вопроса - как я уже показал, извне доступа к foo() в первом случае нет вообще, следовательно вы его объявляете присваиванием, с другой стороны внутри функции у вас идет запрос к foo(), которая ещё всего лишь функция, а не объект foo, естественно foo.v - undefined.
примеры
function test1() {
var foo = new(
function foo() { // foo ----+
this.v = 2; // |
this.bar = { // |
init: function () { // |
return foo.v // foo <----+
}
}
});
console.log(foo.bar.init()); //undefined
}
function test2() {
function foo() {
this.v = 2;
}
console.log(foo.v); //undefined
foo();
console.log(foo.v); //undefined (потому что контекст foo() - не foo)
console.log(this, this.v); //window,2 - объявили глобальный v=2 (контекст foo () - window
}
function test3() {
var bar = new(function foo() {
//это конструктор, он выполняется при new
this.v = 2;
});
console.log(bar.v); //2
}
function test4() {
function foo() {
//это конструктор, он выполняется при new
this.v = 2;
}
foo.prototype.getv = function () {
return this.v;
}
var bar = new(foo);
console.log(bar.v, bar.getv()); //2,2
}
function test5() {
var foo = new(
function foo() {
var that=this;
this.v = 2;
this.bar = {
init: function () {
return that.v; //that потому что иначе контекст будет bar
}
}
});
console.log(foo.bar.init()); //2
}
console.log('==1==');
test1();
console.log('==2==');
test2();
console.log('==3==');
test3();
console.log('==4==');
test4();
console.log('==5==');
test5();