0

I want to fire a function directly, when a new instance of my class is initiated. And it should have access to this. I ve read this question and both of my methods firing, but none have access to the this. (What I realy want accessing are the options ;-) )

I've tried a) in es6 constructor and b) with Prototype Syntax so far. Both fireing, but this is undefined in both cases.

class TypewriterSlider {
constructor(sliderElem, userOptions) {
this.sliderElem = sliderElem;
this.options = {
  ...userOptions,
  split: true, 
}
   this.myInitLettering = function () {
     console.log('a:', this) //->a,  undefined
   }()
  }
}

TypewriterSlider.prototype.initLettering = (function () {
 console.log('b: ', this) // ->b,  undefined
})()


const tws = new TypewriterSlider(elem, {})

I hope someone can help me out. Is it possible to fire a method with access to this, without explicit call? Or is there a better way to achive the desired behavior?

Sorry for my English and many thanks in advance.

Friedrich Siever
  • 417
  • 7
  • 13
  • 1
    What is the benefit of using an IIFE over a method or property accessors? – VLAZ Jan 25 '20 at 19:57
  • Hi, my intention is to create an API, where no explicit .init() call is needed. The API user should provide an elem, some options and option dependend magic should happen after initialisation. – Friedrich Siever Jan 25 '20 at 20:01
  • 1
    That doesn't explain why use an IIFE here. You can just have a factory method for what you describe. – VLAZ Jan 25 '20 at 20:03
  • Does this answer your question? [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – ASDFGerte Jan 25 '20 at 20:03
  • @VLAZ: Ok, I guess the factory approach might be the right approach to achive, what I am looking for. Thank you, I have to dive in factories. – Friedrich Siever Jan 25 '20 at 20:08
  • @ASDFGerte Thank you, this seems to make at least clear, why my approaches cant work. If I get it right this is refering in my case to my methods themselves. – Friedrich Siever Jan 25 '20 at 20:12

0 Answers0