tags:

views:

40

answers:

1

Hi,

I am new to Javascript. I am trying to understand where "this" is bound to using different examples. I am using console.log to print some values as shown below.

function FuncObject(value) { 
    this.answer = value;
    this.get_answer = function () { 
       return this.answer;
    }
};

var f = new FuncObject(42);

var fanswer = f.get_answer;
console.log(fanswer())

console.log prints "function" instead of "undefined". document.writeln seems to print "undefined" which is the right one because this is bound to the window object which does not have answer. Now printing function confuses me. Now I am wondering what i should be using for logging. I am unable to find an explanation for this.

thanks mohan

+1  A: 

Just incase you didn't notice, there's a typo in your posted code of
this.get_answer = funcition ()

With that in mind, I'm not entirely sure of your experience level so let me cover all the bases.

function FuncObject(value) { 
   this.answer = value; 
   this.get_answer = function () { 
     return this.answer; 
   } 
};

var f = new FuncObject(42);

var fanswer = f.get_answer;
console.log(fanswer())

You're setting fanswer = f.get_answer where f.get_answer is a function, so as such it sets fanswer to the function equivalent of this.get_answer.

If you want the return value of f.get_answer you need to call f.get_answer(), which returns 42.

With what you put, console.log(fanswer()) does print undefined as expected.
If you simply do console.log(fanswer) it records it as function, also as expected.

I'm not sure why you would receive function as you stated in your question, because I definitely do not, jsbin.

Ian Elliott
Can you tell me what answer you get ? In the experiment of trying to understand what "this" refers to under different cases, do you agree that in the example above where I store a reference to a method, one needs to do explicit binding using call fanswer.apply(f) for "this" to be bound to "f". Just invoking fanswer() shown above should print undefined. In firefox, if i use document.writeln, it prints undefined and console.log prints "function". What am i missing ?
mohan
Using the code you supplied firebug does not output **function** with console.log, it prints **undefined**. I can't reproduce the error you're talking about with the code provided, it seems to work properly.
Ian Elliott
Sorry about the confusion. It also prints undefined for me. I just got confused with a different log message. Thanks for your time. I will try to be more careful next time
mohan
No problem, happy to help
Ian Elliott