1

I want to create a class named Matrix4 that extends Float32Array. I want to be able to override the Float32Array constructor with a constructor that creates an array of 16 elements (normally I would invoke new Float32Array(16), but now I just want new Matrix4).

// This function should override the Float32Array constructor
// And create a Matrix4 object with the size of 16 elements
var Matrix4 = function() {
    Float32Array.call(this, 16);
};

Matrix4.prototype = new Float32Array;

The error I get from this code is:

Constructor Float32Array requires 'new'

1
  • Hmm... I don't get that error. I get []. Is it possible that error is from somewhere else in your code? Commented Jan 27, 2017 at 15:08

1 Answer 1

4

You can't extend built-in objects like Array or Float32Array using the old-fashioned pre-ES6 syntax. The only way to do it is with a class..extends statement:

class Matrix4 extends Float32Array {
    constructor() {
        super(16);
    }
}

let matrix = new Matrix4;
console.log(matrix.length); // 16
Sign up to request clarification or add additional context in comments.

3 Comments

I had no idea. I've been sticking to the old syntax but I guess it's time to adhere to the new... Thanks!
@Birger There are still times when it's better to use the old style. But this isn't one of them!
Do you mean Javascript classes in general, or just this particular class?

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.