0

I've got a JavaScript object similar to this:

var profile1 = {
    one: "1",
    two: "2"
}

var profile2 = {
    one: "3",
    two: "4"
}

function runLoop () {
    console.log(this.one);
}

profile1.loop = runLoop;
profile2.loop = runLoop;

profile1.loop();

So profile1.loop() will run fine in this case and return a string value of "1". But if I try to run it from the console in either Chrome or Firefox, "1" will still return, but then send out a message of "undefined".

Can this be fixed or am I chasing my tail here?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kaidez
  • 679
  • 8
  • 27
  • Why do you need a fix? If you don't like that the console prints the return value automatically, then perhaps you should use http://jsbin.com or http://jsfiddle.net to test your code. – user113716 Sep 10 '11 at 17:12
  • Are you using frames? Like http://jsfiddle.net or anything like that? – kzh Sep 10 '11 at 18:14
  • Possible duplicate: *[Why does this JavaScript code print "undefined" on the console?](https://stackoverflow.com/questions/10263190/why-does-this-javascript-code-print-undefined-on-the-console)* – Peter Mortensen Oct 20 '20 at 17:08

2 Answers2

3

When you see undefined in the console, it means that the statement you just evaluated did not return a value. So what you are evaluating is not returning a value, despite what you say.

The confusion here is that you are writing this.one to the console, not returning it.

Try this instead:

function runLoop () {
    return this.one;
}
cheeken
  • 33,663
  • 4
  • 35
  • 42
  • numbers1311407 and cheeken: both of your suggestions worked! Thanx VERY much for your help! – kaidez Sep 10 '11 at 20:12
2

I'd say you're chasing your tail in that there's nothing to fix. If you don't want to see the word 'undefined' in the console, you could return anything from that function that you want to see.

e.g.

function runLoop() {
  console.log(this.one);
  return 'loop complete!!!!';
}

> profile1.loop();
1
'loop complete!!!!'
numbers1311407
  • 33,686
  • 9
  • 90
  • 92
  • numbers1311407 and cheeken: both of your suggestions worked! Thanx VERY much for your help! – kaidez Sep 10 '11 at 20:12