-1

Consider this example:

function Dummy(buddy) {
    this._buddy = buddy;
}
Dummy.prototype.greetBuddy = function() {
    console.log('Hello, '+this._buddy);
}

function outerGreet1(dummy) {
    var func = dummy.greetBuddy;
    func();
}
function outerGreet2(dummy) {
    dummy.greetBuddy();
}

Suffice to say this fails to convey why I'm doing this, but is a basic distillation of what I'm encountering. I just fixed a bug in my program that was resulting from this distinction. outerGreet1 will throw an error because it cannot find this._buddy, while outerGreet2 will print the expected result.

I was only copying the function to a local variable for code clarity, but obviously this is a ripe learning experience for me. What exactly is going on here? I'm guessing 'this' ends up referring to the outerGreet1 function? I am coming from Java so I understand that JavaScript only has function scope, but why does creating a new reference to the function change its behavior? I was under the impression that 'this' corresponded to the current scope, and I'm not sure how the reassignment alters scope, so my understanding is flawed somewhere.

Apologies if this is a common JavaScript question but I had great difficulty phrasing my search in a way that turned up any answers.

  • possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Robert Rossmann Mar 04 '15 at 18:19

1 Answers1

0

The this variable depends on how the function is being used.

If you instantiate the function (treat it like a class) then this will refer to the instance of the class:

new outerGreet1(dummy); // `this` is an instance of outerGreet1

If you call it with Function.prototype.call then this will refer to whatever object you passed to the call method:

outerGreet1.call(anotherObjec, dummy); // `this` refers to anotherObject

If you just execute it directly then this may refer to the window or whatever other surrounding scope.

outerGreet1(dummy); // `this` likely refers to the window object

You can also use Function.prototype.bind to wrap your function in a specific scope to help clear things up:

var wrappedExample = outerGreet1.bind(aSpecificObject);
wrappedExample(dummy); // Doesn't matter how it's called, `this` will refer to aSpecificObject

Of course you may want to consider your target browsers before using bind (or use a polyfill).

bvaughn
  • 12,062
  • 37
  • 43