如何在类中执行方法的所有原型链?

时间:2017-05-30 06:47:40

标签: javascript oop prototype

我认为代码将是我问题的最佳解释:

function getMyConstructor(){
   ...
}

const MyConstructor = getMyConstructor({
  x: 0,
  getX: function(){ return this.x; }
},{
  x: 1,
  getX: function(){ return this.__getX() + '  first'; }
},{
  x: 2,
  getX: function(){ return this.__getX() + '  second'; }
},{
  x: 3,
  getX: function(){ return this.__getX() + '  third'; }
});

const myInstance = new MyConstructor;

console.log( myInstance.getX() ) // 3 first second third

有人知道如何实施__getX方法吗?

更新 我已经制作了代码,但我认为它并不那么漂亮

function getMyConstructor() {
    return Array.prototype.reduce.call(arguments, (proto, obj, index, args) => {
        function C() {
        }

        C.prototype = Object.create(proto);

        for (let p in obj) {
            if (!obj.hasOwnProperty(p)) {
                continue;
            }

            C.prototype[p] = obj[p];
            if (index > 0 && typeof obj[p] === 'function') {
                C.prototype['__' + p] = setBaseMethod(p, proto);
            }
        }

        return index === args.length - 1 ? C : C.prototype;
    });

    /**
     * @param {string} method
     * @param {Object} proto
     * @returns Function
     */
    function setBaseMethod(method, proto) {
        let obj = {};
        obj[method] = proto[method];
        obj['__' + method] = proto['__' + method];

        return function () {
            let context = {};
            for (let p in proto) {
                if (this[p] && typeof this[p] !== 'function') {
                    Object.defineProperty(context, p, {
                        get: () => this[p],
                        set: value => this[p] = value,
                        enumerable: true,
                        configurable: true
                    });
                }
            }

            return Object.assign({}, context, obj)[method]();
        }
    }
}

我希望代码建议如何解决问题

1 个答案:

答案 0 :(得分:1)

只是为了好玩,因为你要求原型链:

function chainPrototypes(...objs) {
  return objs.reduce((p, o) => Object.setPrototypeOf(o, p));
}

const myInstance = chainPrototypes({
  x: 0,
  getX() { return this.x; }
}, {
  x: 1,
  getX() { return super.getX() + '  first'; }
}, {
  x: 2,
  getX() { return super.getX() + '  second'; }
}, {
  x: 3,
  getX() { return super.getX() + '  third'; }
});

console.log(myInstance.getX()); // 3  first  second  third

只需将方法定义与super keyword一起使用。