0

Here is the code and fiddle:

var test = function(){
    return{
        value: "hi",
        func1: function(){
            func2();
        }()
    };
}();

function func2(){
    alert(test.value);
}

Can anyone tell me what have I done wrong? I can't get test.value.

SPG
  • 6,109
  • 14
  • 48
  • 79
  • you haven't passed test into your second function func2() uses a different scope, so you need to pass the variable into it – MuppetGrinder Apr 22 '15 at 13:47

4 Answers4

1

Your func2() is called from the IIFE for the func1 property in the IIFE that constructs the object to be assigned to test. Before it assigns to test. And it tries to access the test.value property, on a variable that is yet undefined, and throws a ReferenceError therefore. (See also Self-references in object literal declarations)

I think you are looking for

var test = function(){
    return{
        value: "hi",
        func1: function(){
            func2();
        } // <-- no invocation here, make `func1` a method not `undefined`
    };
}();

function func2(){
    alert(test.value);
}

test.func1(); // "hi"

(updated fiddle)

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

If you run this code you'll be getting an undefined. Why? Well because you haven't given enough time for your test to actually initiate itself ( and the fact that what you're doing this in a synchronous way).

Try this asynchronous solution.

var test = function(){
    return{
        value: "hi",
        func1: function(){
            setTimeout(function(){ func2(); }, 50);
          //you can also just do
          //setTimeout(func2, 50);
        }()
    };
}();

function func2(){
    alert(test.value);
}

Demo

Also notice that you don't return anything to your func1 since it auto invoques itself. Later on if you try to do test.func1() it won't work.

kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
0

The problem is that you assign an object literal to test. However, to build that object, you call func2. That function attempts to access test, but at that point it still is undefined.

Therefore, you should call func2 after assigning the object to test:

var test = function(){
    return {
        value: "hi",
    };
}();
test.func1 = function(){
    func2();
}();
function func2(){
    alert(test.value);
}

However, note that's a bit weird, because the anonymous function doesn't return any value. func2(); test.func1 = undefined would be more natural.

Oriol
  • 274,082
  • 63
  • 437
  • 513
0

As Bergi mentioned you want to use Imidiatelly Invoked Function Expression (IIFE) but your syntax is wrong.

see fixed fiddle

var test = (function(){
    return{
        value: "hi",
        func1: function(){
            func2();
        }
    };
})();

function func2(){
    alert(test.value);
}

With ( at the start of your function and at the end of it before you actually immediately call it

Mior
  • 821
  • 8
  • 16