views:

48

answers:

2

Using the following bit of code:

function Node(){
 ....
 function foo(request){
        for (var name in this ) {
            log(name +" is "+this[name]);
            if(!(name == 'all' || typeof this[name] == 'function')){
                request[name] = this[name];
            }
        }
        return ...
    };
}

I was surprised that when the private function foo is called this doesn't seem to refer to the containing object (an instance of Node). Why is that ?

Of course I could have something like:

 function Node(){
      var ref = this;
      ....
 }

and use ref as this in foo, but is there a way of declaring private methods for which this is a reference to the containing object?

+1  A: 

'this' refers to the object used to call the function, which, by default, is 'window'.

Use foo.apply(this, ...) or foo.call(this, ...) to invoke foo such that 'this' in foo refers to the 'this' that called foo.

The convention I use (to avoid .apply and .call) is:

var me = this;

function foo()
{
    // use 'me'
}

BTW, 'Me' is the keyword for 'this' in VB.NET.

Doug D
"'this' refers to the object used to call the function", but I called foo from a public function in Node ( this.publicFoo = function(){ ... foo(); ...};). How come then that this still refers to window? Cheers
jd
'this' refers to the object on the left side of the "." when a method is called. But if called without "." (e.g., foo();) then it implies window.foo(); It doesn't matter where it's defined, but how it is called.
Doug D
A: 

the implementation of 'this' was incorrect but was not 'fixed' leading to all of the confusion and workarounds.

your var ref=this; is exactly how you would maintain a reference to your object for use in it's public/priveledged members. Douglas Crockford (google it) uses var that=this;.

Sky Sanders