-1

I created an Object called Survey and added a prototype function to it, and when I console log this inside the prototype function the log shows window object instead of parent Survey Object.

function Survey(questions = []) {
  this.__questions__ = questions;
};
Survey.prototype.testFunction = () => {
  console.log(this);
  return this.__questions__;
}
// Create your object here
const SUR = new Survey(['1','2']);

SUR.testFunction(); // this prints [[Window]] Object instead of Survey

Expected result would be Survey object

Vinayak humberi
  • 191
  • 3
  • 8
  • 2
    when you use an arrow function you are changing the way the this keyword is bound, use a normal function instead "Survey.prototype.testFunction = function () {" – user2950720 Jun 01 '19 at 20:37
  • 1
    It's because you're using an array function. Array function don't have a this-context so they will use the this-context from outside. (In this case global/window) – dejakob Jun 01 '19 at 20:38
  • **this** is explained in the doc : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions `although without its own bindings to the this` – Mister Jojo Jun 01 '19 at 20:43

2 Answers2

2

It is because you used an Arrow function. In arrow function, this will be reference to outside. Just use a normal function instead.

Survey.prototype.testFunction = function() {
  console.log(this);
  return this.__questions__;
}
BigLiao
  • 507
  • 3
  • 9
2

The problem is over here:

Survey.prototype.testFunction = () => {}

Arrow functions don't have a this-context and it will use the this-context from outside of the method. Since no other this-context is defined, it will be the window object.

The fix is very easy: use a regular function:

Survey.prototype.testFunction = function () {}
dejakob
  • 2,062
  • 14
  • 21