1

I believe this can be solved using an arrow-function, but I'm not sure how. I would like to access this.props inside of the render Function. I know I could pass it over as an argument, but would rather not. Is this possible using arrow functions? If so, what do I need to change?

class View {
  constructor(options) {
    this.options = options;
  }
  render(el, props = {}) {
    this.props = props;
    el.innerHTML = this.options.render(el);
  }
} 

var Test = new View({
  render() {
    return `${this.props.test}`
    //
    // Also, tried ${props.test} in my template literal
    //
  }
});

Test.render(document.getElementById("main"), {
    test:"123"
})
Eric Harms
  • 827
  • 1
  • 7
  • 13
  • No, this is exactly *not* possible using arrow functions. You are looking for `this.options.render.call(this, el)`. – Bergi Jun 21 '17 at 03:32
  • Related: [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](https://stackoverflow.com/q/34361379/218196) – Felix Kling Jun 21 '17 at 04:15

2 Answers2

3

Arrow functions allow you to access the this of the external closure, not of the calling function space. A defining point of functions is to isolate it from the callee's variables. Arrow functions simply make the context, or the this object, to be equal of it's definition closure. Thus

var that = this;
(() => console.log(that === this))();

Will print true, while

var that = this;
(function(){console.log(that === this)})();

Will print false The reason that the arrow's function can access the this context, is because its defined there, not because it's called there.

The only way to force the context object is by using Function.prototype.call or Function.prototype.apply

f.khantsis
  • 3,256
  • 5
  • 50
  • 67
1

Do you need the this.props = props allocation? You could have something like this.

class View {
  
  constructor(options) {
    this.options = options;
  }

  render(el, props = {}) {
    el.innerHTML = this.options.render(props);
  }
}

var test = new View({ render: x => `${x.test}` });

test.render(document.getElementById("main"), { test:"123" });
<div id="main"></div>
Daniel Ormeño
  • 2,743
  • 2
  • 25
  • 30