-1

Нужна помощь с реализацией такой вот задачи - функция должна принять массив функций и соединить их в цепочку наследования, после чего новый объект должен иметь доступ к методам переданных прототипов

const ExtendedSquare = chain(Square, Polygon, Shape);
1

1 ответ 1

0

Как-то так можно нахимичить:

function chain(...fs) {
  var ps = fs.map(f => f.prototype)
  
  fs.reverse()
  ps.unshift(Object.create(null))

  function Res(...args) {
    var me = Object.create(null)

    for (var f of fs) {
      Object.setPrototypeOf(me, f.prototype)
      me = f.apply(me, args) || me
    }
    
    Object.setPrototypeOf(me, new.target.prototype)
    
    return me
  }

  Res.prototype = new Proxy(ps[0], {
    getOwnPropertyDescriptor(target, name) {
      var res

      for (var p of ps) {
        if (res = Object.getOwnPropertyDescriptor(p, name) /* assignment */) {
          break
        }
      }
      
      return res
    },
    
    ownKeys(target) {
      return Array.from(new Set(ps.flatMap(p => [Object.getOwnPropertyNames(p), Object.getOwnPropertySymbols(p)])))
    },
    
    has(target, name) {
      for (var p of ps) {
        if (name in p) {
          return true
        }
      }
      
      return false
    },
    
    get(target, name, receiver) {
      for (var p of ps) {
        if (Object.hasOwnProperty.call(p, name)) {
          return p[name]
        }
      }
      
      for (var p of ps) {
        if (name in p) {
          return p[name]
        }
      }
    },
  })

  return Res;
}

function X(x) { this.x = x }
X.prototype.getX = function () { return this.x }

function Y(x, y) { this.y = y }
Y.prototype.getY = function () { return this.y }

function Z(x, y, z) { this.z = z }
Z.prototype.getZ = function () { return this.z }

var Q = chain(Z, Y, X)
var obj = new Q(1, 2, 3)

console.log(obj.x, obj.y, obj.z)
console.log(obj.getX(), obj.getY(), obj.getZ())

console.log(obj + "")

Y.prototype.toString = function () { return this.x + " " + this.y }
console.log(obj + "")

X.prototype.toString = function () { return this.x }
console.log(obj + "")

Z.prototype.toString = function () { return this.x + " " + this.y + " " + this.z }
console.log(obj + "")

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.