Reputation: 1331
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
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
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
Reputation: 887305
this
can change depending on how you call the function:
var funnyB = obj.b;
funnyB(); //this is window
Upvotes: 2