-2

I just started to learn ES6 so I used Babel to compile that code, but when I assign this keyword to a variable inside a prototype method it compiled to undefined

is this a bug? or problem with my code?

ES6 Code

function Prefixer(prefix) {
    this.prefix = prefix;
}

Prefixer.prototype.prefixArray = arr => {
    let self = this;
    return arr.map((x) => {
        console.log(self.prefix + x);
    });
}

var pre = new Prefixer("Hello ");
pre.prefixArray(['Jeeva', 'Kumar']);

Babel Compiled Code

'use strict';

function Prefixer(prefix) {
    this.prefix = prefix;
}

Prefixer.prototype.prefixArray = function (arr) {
    var self = undefined;
    return arr.map(function (x) {
        console.log(self.prefix + x);
    });
};

var pre = new Prefixer("Hello ");
pre.prefixArray(['Jeeva', 'Kumar']);

Code Snippet Screenshot

Jeeva
  • 1,483
  • 1
  • 13
  • 18
  • 2
    Hello, and welcome to Stack Overflow. Please be aware that we very much dislike code in images, and prefer to have code we can actually copy and paste, or even execute. Indent code with four spaces to show as code. You can do it automatically by selecting your code visually, then hitting `Ctrl-K` (or `Cmd-K` on Mac). – Amadan Jul 28 '17 at 04:14
  • 1
    Because you're using an arrow function, `this` is inherited from the defining scope. You should **not** use arrow functions for prototype methods – Phil Jul 28 '17 at 04:16
  • Oh ok, so there is a limitation with arrow functions – Jeeva Jul 28 '17 at 04:19

1 Answers1

0

See this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Shortly, in arrow function, this has no binding.

Yonggoo Noh
  • 1,486
  • 3
  • 16
  • 34
  • Thanks, I didn't know it was caused by the arrow function, I thought the arrow function is just a normal function allow to write less code, but now I got it, it's a totally different from normal function – Jeeva Jul 28 '17 at 04:32