1

How come this doesn't alert "http://127.0.0.1/sendRequest"? (Available at http://jsfiddle.net/Gq8Wd/52/)

var foo = {
    sendRequest: function() {
        alert(bar.getUrl());
    }
};                    

var bar = {
    getUrl: function() {
        return 'http://127.0.0.1/' + arguments.callee.caller.name;
    }
};

foo.sendRequest();
Jeremy
  • 1
  • 85
  • 340
  • 366
user979672
  • 1,803
  • 3
  • 23
  • 32

4 Answers4

2

Putting a value in an object literal, as you're doing, doesn't affect the value at all.

var foo = {
    sendRequest: ...

The function value is only affected by the function expression, which doesn't contain a name.

             ... function() {
        alert(bar.getUrl());
    }

You need to include the name you want in the function expression itself [fiddle].

var foo = {
    sendRequest: function sendRequest() {
Jeremy
  • 1
  • 85
  • 340
  • 366
  • 2
    Just be aware that you *may* run into issues using named function expressions in this way: http://kangax.github.com/nfe/#jscript-bugs – Sean Vieira Nov 03 '11 at 17:55
2

If you do this:

var foo = {
    sendRequest: function() {
        alert(bar.getUrl());
    }
};                    

var bar = {
    getUrl: function() {
        return  arguments.callee;
    }
};

foo.sendRequest();

You will notice that the function doesn't have name which is true:

function() {

This is anonymous function.

You can name you method : sendRequest: function myMethodName() {

Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
2

Although the function is stored under the object property foo.sendRequest, and thus can be invoked via foo.sendRequest(), that function itself doesn't actually have a name. That's why arguments.callee.caller.name is empty.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

Because the function that is calling the function being called is an anonymous function (and hence, has no name).

Try:

function sendRequest() {
    alert(bar.getUrl());
}

var foo = {
    sendRequest: sendRequest
};                    

var bar = {
    getUrl: function() {
        return 'http://127.0.0.1/' + arguments.callee.caller.name;
    }
};

foo.sendRequest();
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293