Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript class without this, that, self, etc

Tags:

javascript

Is it possible to create JavaScript class without using 'this' keyword? Expressions like

var self = this;
...
self.property = value;

is also prohibited. I dont want to think about context and use only vars.

Take a look at this simple class:

function Timer() {
  var interval = 0;
  var count = ++Timer.totalCount;

  function setInterval(val) {
    interval = val;
  }
  function run() {
    setTimeout(done, interval);
  }
  function done() {
    var div = document.createElement('div');
    div.innerHTML = 'Timer #' + count + ' finished in ' + interval + ' ms';
    document.body.appendChild(div);
  }

  return {
    setInterval: setInterval,
    run: run
  }
}
Timer.totalCount = 0;

var t1 = new Timer();
var t2 = new Timer();
var t3 = new Timer();

//how to directly set interval value without set function?
t1.setInterval(3000);
t2.setInterval(2000);
t3.setInterval(1000);

t1.run();
t2.run();
t3.run();

This class does not use 'this' at all.

Is it correct?

Can I create real classes like that? Is there potential problems?

How to create property in this class without get/set function?

Is that class possible to extend using inheritance?

like image 428
Alexey Obukhov Avatar asked Sep 04 '25 16:09

Alexey Obukhov


1 Answers

First of all, this is a basic thing in JavaScript. It's very recommended that you can understand it and reason about its context.

If you want a more "traditional" OOP code and are able to use ES6/ES2015 (or transpiling with Babel), all the reasoning about this also becomes easier and all the code more clean. Here's your sample rewritten with ES2015, including the inheritance part:

class Timer {
  constructor(count, interval) {
    this.interval = interval
    this.count = count
  }

  run() {
    setTimeout(() => {
      const div = document.createElement('div')
      div.innerHTML = `Timer #${this.count}
        finished in ${this.interval} ms`
      document.body.appendChild(div)
    }, this.interval)
  }
}

class OneSecondTimer extends Timer {
  constructor(count) {
    super(count, 1000)
  }
}

const t1 = new Timer(1, 3000)
const t2 = new Timer(2, 2000)
const t3 = new OneSecondTimer(3)

t1.run()
t2.run()
t3.run()
like image 160
Erick Petrucelli Avatar answered Sep 07 '25 07:09

Erick Petrucelli