2

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?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

this can change depending on how you call the function:

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.