0

В чем разница между

foo = new(function foo(){
    this.v = 2;
    this.bar={
       init:function(){return foo.v}
    }
})

и

foo = new(function foo(){
    this.v = 2
});
foo.bar={
   init:function(){return foo.v}
}

в первом варианте foo.bar.init() возвращает undefined, во втором 2.

Вывод консоли:

foo1
foo1 {v: 2, bar: Object}
bar: Object
init: function (){return foo1.v}
v: 2

foo2
foo2 {v: 2, bar: Object}
bar: Object
init: function (){return foo2.v}
v: 2

foo2.bar.init();
2

foo1.bar.init();
undefined

foo1.bar.init
function (){return foo1.v}

foo2.bar.init
function (){return foo2.v}

foo2.bar
Object {init: function}

foo1.bar
Object {init: function}
1
  • странное здесь только то, что область видимости в которой видно имя функции определилась круглыми скобками jsfiddle.net/oceog/SaF7d и даже так: jsfiddle.net/oceog/SaF7d/4
    – zb'
    13 янв 2014 в 2:14

1 ответ 1

3

отсюда

There is a distinction between the function name and the variable the function is assigned to:

  1. The function name cannot be changed, while the variable the function is assigned to can be reassigned.
  2. 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();

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.