0

I was trying to experiment with some JavaScript code. I am not sure why the ES6 syntax fails.

String.prototype.spacify = function() {
  console.log(this.split('').join(' '));
}

'hello world'.spacify();  

^^ This works GREAT! But, When I do this

String.prototype.spacify = () => {
  console.log(this.split('').join(' '));
}

'hello world'.spacify();  

When I convert the function to Arrow function, I get this.split is not defined. I didn't understand. Is arrow syntax doing something special with scoping?

Please enlighten!

TechnoCorner
  • 4,151
  • 8
  • 27
  • 62
  • A google reveals many takes on `this` https://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/ – mplungjan Sep 26 '17 at 05:12

2 Answers2

2

In arrow function the context of this refers to the outer this. Here the this of the function test is equal to the this in the arrow function.

arrow function doesn't create it's own context, it just takes the outer context

function test() {


     String.prototype.spacify = () => {
         console.log(this.split('').join(' '));
     }

}
Suren Srapyan
  • 57,890
  • 10
  • 97
  • 101
0

In arrow functions, the scope does not change.

Meaning:

const globalThis = this;

String.prototype.spacify = () => {
  // this === globalThis
  ...
}
Mike Rapadas
  • 4,347
  • 2
  • 26
  • 20