Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[class] remove this instanceof itself checks #281

Open
jimmywarting opened this issue Oct 22, 2018 · 3 comments
Open

[class] remove this instanceof itself checks #281

jimmywarting opened this issue Oct 22, 2018 · 3 comments
Labels

Comments

@jimmywarting
Copy link

const util = require('util');
const EventEmitter = require('events');

function MyStream() {
  if (!(this instanceof MyStream)) {
    return new MyStream();
  }
  
  EventEmitter.call(this);
}

util.inherits(MyStream, EventEmitter);

MyStream.prototype.write = function(data) {
  this.emit('data', data);
};

const stream = new MyStream();

Is transformed to

const util = require('util');
const EventEmitter = require('events');

class MyStream extends EventEmitter {
  constructor() {
    if (!(this instanceof MyStream)) {
      return new MyStream();
    }

    super();
  }

  write(data) {
    this.emit('data', data);
  }
}

const stream = new MyStream();

The problem with it are

  • this is used before calling super()
  • this instanceof MyStream will always be true (cuz you can never invoke MyStream without the new keyword)
    • I think the if check should be removed altogether. Leaving it with just the super() left
@uniibu
Copy link
Contributor

uniibu commented Oct 22, 2018

There are a lot of other bugs for the class transform, and like nene said, it should be rewritten rather than adding fixes over fixes.

On the side note, Classes can be invoked using its static methods returning a new instance of the class, hence no new is needed.

@nene
Copy link
Collaborator

nene commented Oct 22, 2018

@jimmywarting The first bug relating to super() is already known: #186

Regarding this instanceof check. When some code relies on this, then converting this function to class was really a mistake. So instead of removing this check I'm leaning towards detecting it and preventing the class transform from happening in the first place.

@pitust
Copy link

pitust commented Mar 18, 2020

Or transfarming the caller to use the new operator

@nene nene added the bug label Mar 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants