1
// global scope

var sayMyFavoriteColor = function(adj){
    return 'My ' + adj + ' color is ' + this.favoriteColor; + '!'
};

var callFnTest = function (opts) {
  return sayMyFavoriteColor.call(this, opts);
};

this.favoriteColor = 'Brown'; //adding a global variable to window
i.e. var favoriteColor = 'Brown'

callFnTest('most disliked')
"My most disliked color is Brown"

My question is because we are passing this to call it is pointing to the window, correct?

Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141
  • @KenY-N My apologies! – Antonio Pavicevac-Ortiz Jan 12 '17 at 16:27
  • In your example, `this` inside `sayMyFavoriteColor` refers whatever `this` is inside `callFnTest`. Since it is called as `callFnTest(...)`, `this` will refer to the global object, or `undefined` if strict mode is enabled. I recommend to read an article about `this` (such as https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) if you haven't yet. – Felix Kling Jan 12 '17 at 16:30
  • @FelixKling So one should just zero in on the `return sayMyFavoriteColor.call(this, opts);` statement. In other words if we had an object with a property `favoriteColor : 'Plaid'` in the context in place of our hard coded `this` reference. The color would be Plaid? RIght? – Antonio Pavicevac-Ortiz Jan 12 '17 at 16:42
  • Yes. The first argument passed to `.call` becomes the `this` value of the function that `.call` is called on. – Felix Kling Jan 12 '17 at 16:43

1 Answers1

0

It doesn't change. You can only use the this keyword when you use an instance of the class. Basically, if you call a.whateverFunction(), a is this.

PMARINA
  • 304
  • 4
  • 17