@serhiops
Python/JavaScript/C++

Как правильно унаследовать массив через прототипы?

Конструктор Array не срабатывает так как ожидалось:
'use strict';

const RevercedArray = function(...args) {
  Array.apply(this, args);
};

Object.setPrototypeOf(RevercedArray.prototype, Array.prototype);

const arr = new RevercedArray(1, 2, 3);

console.log(arr); // RevercedArray {}

UPD
Я хочу сделать что-то похожее на это:
const Rectangle = function(x, y, width, height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
};

Rectangle.prototype.area = function() {
  return this.width * this.height;
};

const Square = function(x, y, length) {
  Rectangle.call(this, x, y, length, length);
};

Object.setPrototypeOf(Square.prototype, Rectangle.prototype);

const sq = new Square(1, 2, 3);
console.log(sq); // Square { x: 1, y: 2, width: 3, height: 3 }
  • Вопрос задан
  • 75 просмотров
Решения вопроса 1
@serhiops Автор вопроса
Python/JavaScript/C++
Проблема решена. Ссылка на документацию: https://developer.mozilla.org/en-US/docs/Web/JavaS...
Рабочий код:
'use strict';

const RevercedArray = function(...args) {
  return Reflect.construct(Array, args, new.target);
};

Object.setPrototypeOf(RevercedArray.prototype, Array.prototype);

const arr = new RevercedArray(1, 2, 3);

console.log(arr); // RevercedArray(3) [ 1, 2, 3 ]
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы