0

I am trying to implement a throttle method inside a class that takes as the second argument some class properties but I can't access the class properties because this is undefined.

I have reproduced the code in a simpler manner to demonstrate the issue:

function someThrottleFunction(a, b) {
  // doesn't really matter what is in here
}

class cname {
  constructor(prop1) {
    this.prop1 = prop1;
  }
  func = someThrottleFunction(() => {}, this.prop1.time);
}

let a = new cname({ time: 3000 });

you can see a live code error demo here: https://codesandbox.io/s/x7yqy933qq

Any suggestions on how to rewrite this in a working manner are greately appreciated.

3
  • @paulsm4 I don't know if this is scientifically backed, but anecdotally it's easier on the eyes for some (most?) people. Commented Dec 27, 2018 at 0:32
  • @paulsm4 Maybe it's also because of the AMOLED screens which doesn't drain power when displaying black content Commented Dec 27, 2018 at 0:36
  • Thank you, Alex - that makes sense. Commented Dec 27, 2018 at 2:08

2 Answers 2

3

The problem is that the func is assigned to before the constructor runs:

function someThrottleFunction(a, b) {
  // doesn't really matter what is in here
}

class cname {
  constructor(prop1) {
    console.log('constructor running');
    this.prop1 = prop1;
  }
  func = (console.log('func being assigned to'), someThrottleFunction(() => {}, this.prop1.time));
}

let a = new cname({ time: 3000 });

You might assign at the end of the constructor instead:

function someThrottleFunction(a, b) {
  // doesn't really matter what is in here
}

class cname {
  constructor(prop1) {
    this.prop1 = prop1;
    this.func = someThrottleFunction(() => {}, this.prop1.time);
  }
}

let a = new cname({ time: 3000 });

Sign up to request clarification or add additional context in comments.

Comments

1

It looks like you intended for func to be a function:

function someThrottleFunction(a, b) {
  console.log(b)
}

class cname {
  constructor(prop1) {
    this.prop1 = prop1;
  }
  func() { 
    someThrottleFunction(() => {}, this.prop1.time);
  }
}

let a = new cname({ time: 3000 });
a.func()

or

function someThrottleFunction(a, b) {
  console.log(b)
}

class cname {
  constructor(prop1) {
    this.prop1 = prop1;
  }
  func = () => { 
    someThrottleFunction(() => {}, this.prop1.time);
  }
}

let a = new cname({ time: 3000 });
a.func()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.