Aljoša Srebotnjak
Aljoša Srebotnjak

Reputation: 1331

calling object members - javascript

If i have:

var obj={
    a:function(){obj.b();},
    b:function(){this.a();}
};

is there any difference in calling object methods with "this" or referring directly to the object itself because it is on the same scope as the method?

Upvotes: 2

Views: 90

Answers (3)

Joseph
Joseph

Reputation: 119837

Depends

this can take many forms, making it unpredictable:

  • In a normal function call, like funcName(), this is the global object. In browsers, it's the window object.

  • In a normal function call where the function uses "use strict", this is undefined.

  • For a function used as a constructor, like var instance = new ConstructorFunction(), this will refer to the instance object created from that constructor.

  • For object literals, this is the immediate object literal enclosing the function.

  • When called by call(context,args...) or apply(context,[args...]), this is whatever context is.

Upvotes: 3

Greg Franko
Greg Franko

Reputation: 1770

In the object literal context that you provided, there is no logical difference. The this keyword points to the obj variable, since this is a reference to the object that the function is a property/method of.

Upvotes: 0

SLaks
SLaks

Reputation: 887305

this can change depending on how you call the function:

var funnyB = obj.b;
funnyB();  //this is window

Upvotes: 2

Related Questions