2

I'm trying to create a subclass of NodeJS's buffer. I tried the following:

const SubClass = Object.create(Buffer)
SubClass.prototype.isZero = function () { 
    for(const value of this.buffer) { // Fails on this line 
        ...
    }
}

Then I do the following

SubClass.from([0, 0]).isZero()

It throws

TypeError: undefined is not a function

But this.buffer is defined. So whats the problem (maybe an iterator problem?)? Am I doing something wrong with extending the buffer?

3
  • 1
    If it fails at that line, it must be. this.buffer[Symbol.iterator] must not be a function. Commented Jul 4, 2017 at 15:33
  • But why? this.buffer is defined but the iterator of it not? How can I fix it? Commented Jul 4, 2017 at 15:50
  • Are you sure it fails at that line? I'd figure it actually fails at isZero call, because from will return an instance of Buffer all the time no matter what. isZero then shouldn't exist there. Commented Jul 4, 2017 at 15:52

1 Answer 1

2

The Buffer isn't a class to extend as you're expecting - it's worthwhile to read the modules function which you are having problems with:

https://github.com/nodejs/node/blob/master/lib/buffer.js#L172

Extending the Buffer class will duplicate all the methods which initialise new instances of Buffer instead of your new SubClass. So you won't be able to extend the buffer class for your defined behaviour. Alternatively, you can wrap it with a class to create a similar interface.

class MyBuffer {
  constructor(arg) {
    this.buffer = Buffer.from(arg)
  }

  static from(arg) {
    return new MyBuffer(arg);
  }

  isZero() {
    for(const value of this.buffer) { 
      // Fails on this line 
      console.log(value)
    }
  }
}

Then using your preferred syntax:

MyBuffer.from([0, 0]).isZero()
Sign up to request clarification or add additional context in comments.

2 Comments

Hopped there is a way around doing that but thanks for your answer :) I think you couldn't extend the Buffer before the API change too, if so the first part of your answer is incorrect. You can still use new Buffer(..) but it's deprecated.
You could subclass with libraries but they were all more operable implementations of above - hence the former comment - as most of those libraries won't work after the implementation change.

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.