-3

I can't understand 'this' in Readable.call(this) and how they work. Please explain me!

var Readable = require('stream').Readable;
var util = require('util');

function Counter() {
    Readable.call(this);
    this._max = 1000;
    this._index = 1;
}
util.inherits(Counter, Readable);

Counter.prototype._read = function () {
    var i = this._index++;
    if (i > this._max)
        this.push(null);
    else {
        var str = ' ' + i;
        this.push(str);
    }
};
jfriend00
  • 580,699
  • 78
  • 809
  • 825
J. Colar
  • 1
  • 2
  • the `this` refers to `Counter` 'class.' – Bagus Tesa Apr 22 '18 at 02:26
  • Possible duplicate of [How does the "this" keyword in Javascript act within an object literal?](https://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal) – slebetman Apr 22 '18 at 02:31

1 Answers1

0

In ES5, Readable.call(this); is how you call the constructor of your base class from the derived constructor.

What this does is tell the interpreter to call the Readable() function and set the this pointer in that function to this which points at the newly created object. This then allows the base constructor to initialize its portion of the object before you execute the rest of your constructor and before the newly created object is returned to the caller.

Using this scheme, there's one object and the constructors execute from top down (base object constructor first, then derived object constructor, but it only works this way because of the convention where each constructor calls its base constructor before executing any of its own code.

With an ES6 class declaration, you would just use super(); and the interpreter takes care of the details for you. The user of super() in ES6 enforces that you can't even reference this in your constructor before you call super() (that will result in an error).

For more information about how the this pointer is set when calling functions, see How this is set for functions. And, you can read about .call() here on MDN.

jfriend00
  • 580,699
  • 78
  • 809
  • 825