If you randomly use this
inside of a function which is NOT a constructor, then you will get one of a few different results:
function callThis () { return this; }
callThis(); // returns window object
var Bob = { func : callThis };
Bob.func(); // returns Bob
callThis.call(Bob); // returns Bob
Call is a method which is used to determine the context of the call.
If the call's context can not be determined by:
a. What's in front of the "." (Bob.func();
)
b. What's explicitly passed into .call()
, .apply()
or .bind()
Then it's set to window
.
That is how context is resolved.
So if you have a specific object in mind for this
, then your solutions are as follows:
function objMethod () {
var self = this;
function doStuff () {
self.otherFunc();
self.otherProperty = "bob";
}
doStuff();
}
var myObj = { myMethod : objMethod };
myObj.myMethod();
myObj
calls objMethod
with the context set to myObj
.
objMethod
saves a reference to the current context (myObj
) as self
. doStuff
uses the reference to modify the properties of the referenced object.
function outer () {
function inner () { this.property = "Bob"; }
inner.call(this);
}
var obj = {};
outer.call(obj);
Here, outer
is passed a context, using .call()
.
Then inner
is passed the this
of outer
, again, using .call()
var bob = { name : "Bob" };
function sayName () { console.log(this.name); }
var bobFunc = sayName.bind(bob);
bobFunc();
Here, we use .bind()
to create a version of sayName where this
is always set to bob
.
You can feel free to mix and match these systems all you'd like (and when dealing with async programming, you likely will).