2

In old javascript class you could create values that would always work, how do you do this in es6 classes?

function B() {
  var text = "B"
  var self = this // store this so we don't lose it

  this.speak = function() {
    return alert(self.text)
  }
}

var b = new B();
var f = {}
f.pointer = b.speak
f.pointer()
b.speak()

How do you do this in es6?

class A{
  constructor() {
    this.text = "A";
  }
  speak(){
    alert(this.text) // this is not correct how to fix?>!!
  }
}

var a = new A();
var f = {}
f.pointer = a.speak
f.pointer()
a.speak()
Code Maniac
  • 35,187
  • 4
  • 31
  • 54
KillerKiwi
  • 313
  • 1
  • 3
  • 8
  • 2
    `f.pointer = a.speak.bind(a)` – Phil Aug 26 '19 at 04:57
  • 1
    Regarding the duplicate... while the question differs a little to this one, the answers (especially the accepted one) still apply – Phil Aug 26 '19 at 05:00
  • After reading the accepted answer check [this answer](https://stackoverflow.com/a/52457192/402037) which has a solution for your `class { ... }` case – Andreas Aug 26 '19 at 05:03
  • So es6 arrow functions (which are NOT in es6) look like the only real answer here as bind requires the original object which is not good... This seems to be a real issue with no good answer at the moment... as arrow functions on classes are not currently supported in browsers Its almost better to stick with the old syntax... – KillerKiwi Aug 26 '19 at 21:10
  • I ended up using this package https://www.npmjs.com/package/auto-bind-inheritance a bit of a hack but better than manually binding all calls – KillerKiwi Aug 26 '19 at 21:20
  • _"so es6 arrow functions (which are NOT in es6)"_ - What? -> https://www.ecma-international.org/ecma-262/6.0/#sec-arrow-function-definitions, _"as arrow functions on classes are not currently supported in browsers"_ - What? Every browser ([IE is not a browser](https://www.zdnet.com/article/microsoft-security-chief-ie-is-not-a-browser-so-stop-using-it-as-your-default/)) supports [classes](https://caniuse.com/#feat=es6-class) and [arrow functions](https://caniuse.com/#feat=arrow-functions) (and no, the combination of both doesn't change anything) – Andreas Aug 28 '19 at 17:19
  • Sorry i meant arrow function as a property on a class, it does not currently work with any browser natively – KillerKiwi Sep 02 '19 at 21:07

0 Answers0