0

I am trying to create two objects from one class. The objects add scroll listeners to the document and change change the divs provided by the instance.

However, creating a second class instance ignores the first and does not do anything to the provided div.

class MyClass{
  constructor(parameter){
    self = this;
    self.parameterA = parameter;
    self.myClassMethod = self.myClassMethod.bind(self);
    document.addEventListener("scroll", self.myClassMethod)
  }

  myClassMethod(){
    $('.class').each(function(){
      console.log(self.parameter); //Returns only the second instance's parameter (parameter B)

     $(this).children('.'+self.parameter).fadeIn('slow');//only fades in second instance
    })
  }

}

var testA = MyClass(parameterA);
var testB = MyClass(parameterB);

Edit: In this code I have to use the this of the constructor and the .each() function.

auto
  • 1,062
  • 2
  • 17
  • 41
  • 1
    Your `self` is implicitly global. Use `this` instead – CertainPerformance Jul 08 '19 at 22:19
  • Sorry, I'm not sure what you mean? Should I use another variable name other than `self`? Sorry, new to JS classes. – auto Jul 08 '19 at 22:20
  • You don’t need `self` at all in `constructor`, and you do need `var self = this;` in `myClassMethod`. Using a variable name other than `self` would also help a lot, yep (because then strict mode will give you errors when you make a mistake, and classes are always in strict mode). – Ry- Jul 08 '19 at 22:20
  • If you want to be able to access `this` inside the `each` callback, use an arrow function instead – CertainPerformance Jul 08 '19 at 22:20
  • Yes, that is why I have `self`, to be able to access the constructor `this` in the `each()` – auto Jul 08 '19 at 22:21
  • That's an antipattern IMO, see https://github.com/airbnb/javascript#naming--self-this – CertainPerformance Jul 08 '19 at 22:28
  • I could not make this work. My solution was to bring the each() function out of the class and use it to pass each element ID into the class constructor instead. – auto Jul 10 '19 at 19:40

0 Answers0