Regarding private javascript method

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 a private function foois called this, it does not seem to refer to the containing object (instance Node). Why is this?

Of course, I could be something like:

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

and use refas thisin foo, but is there a way to declare private methods for which thisis a reference to the containing object?

+3
source share
2 answers

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

foo.apply(this,...) foo.call(this,...) foo, 'this' foo 'this', foo.

, ( .apply .call):

var me = this;

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

BTW, 'Me' - 'this' VB.NET.

+1

'this' , "", .

var ref=this; - , / . (google it) var that=this;.

0

Source: https://habr.com/ru/post/1732702/


All Articles