Yashua Yashua - 6 months ago 9
Javascript Question

this scope in arrow function prototypes

Its my understanding that this doesn't work (this is a contrived example - see the RxJS for what I am actually running):

function Foo() {
this.name = 'Johnny Cash'
}

Foo.prototype.who = () => {
console.log(this.name) // undefined
};

var foo = new Foo();

foo.who()


As
this
doesnt have the correct scope. However this page (last 2 bottom examples) on RxJS docs use it. How are they running this code?

Is the code on the RxJS page incorrect? or do I need to run through some kind of Babel plugin ( I already tried running through babel-require and babel-polyfill with same effect)

Answer

Examples on that page are broken.

It would be fair to assume it was never run as it is currently posted, since it has the syntax error in the

var subcription = emitter.listen('data', data => console.log(`data: ${data}`);

line (not paired parentheses).

After it is fixed and run - there are other exceptions about reading properties of undefined, which is this inside the beforementioned arrow functions.

Comments