2

I am just playing around with arrow functions, and tried using them as a property in an object literal, like so:

var obj = {
  a: () => {
    return this;
  },
  b: function () {
    return this;
  },
};

But, when I test this, I can't quite explain what the this returned from obj.a() is.

console.log(obj.a()); //=> {}
console.log(obj.b()); //=> { a: [Function], b: [Function] }

Is it obj's prototype?

ptf
  • 2,770
  • 8
  • 29
  • 64

3 Answers3

3

Most likely this will refer to the nodejs default object (the equivalent of window). It may be defined as something else depending on what scope your object is placed in.

If you have use strict in your project this will be undefined.

Community
  • 1
  • 1
Undefined
  • 10,466
  • 5
  • 35
  • 61
2

The fat arrow function gives you back the parent's scope. means that in this case is not useful because it would give you back the wrong scope.

The fat arrow is useful when you have a callback that you want to get in the same scope. (remember the var self = this?)

var obj = {
    txt: 'TEXT',
  a: function (cb) {
    return cb();
  },
  b: function () {
      var self = this;
      this.a(function() { // Normal funciton, you need the self
          //console.log(val);
          console.log(this.txt)
          console.log(self.txt);
      })
  },
  c: function () {
      this.a(() => {
          console.log(this.txt)
      })
  },
};

console.log('--- B')
obj.b();
console.log('--- C')
obj.c();
DevAlien
  • 2,252
  • 13
  • 16
1

the return object in a is the global object, if you set use strict it will be undefined.

var obj = {
  a: () => {
//this = global scope
    return this;
  },
  b: function () {
    return this;
  },
};
Saar
  • 2,216
  • 1
  • 13
  • 14
  • As others mentioned, this also depends where your object was called from, in this case it's the global scope – Saar Sep 18 '15 at 07:18