Javascript-форум (https://javascript.ru/forum/)
-   Оффтопик (https://javascript.ru/forum/offtopic/)
-   -   Множественное наследование, супер методы, наследование дескрипторов (https://javascript.ru/forum/offtopic/45583-mnozhestvennoe-nasledovanie-super-metody-nasledovanie-deskriptorov.html)

Octane 16.03.2014 20:30

честно говоря сразу хотел назвать прототипы с маленькой буквы, потом зачем-то оставил, как в примере по ссылке

nerv_ 16.03.2014 21:04

бывает :)

Я вот теперь не могу тему переименовать. Только название получилось :D

Octane 16.03.2014 21:17

с чпу наверное уже ничего не сделать

nerv_ 17.03.2014 21:46

Цитата:

Сообщение от Octane
с чпу наверное уже ничего не сделать

за ошибки приходиться платить. Ну да ладно :)

Maxmaxmaximus11 19.03.2014 13:18

Ща вам батя покажет класс

Octane 19.03.2014 14:26

о нееет, пощади!

Maxmaxmaximus11 19.03.2014 17:01

новая версия Class, к суперметодам обращаемся через $methodName. если свойство начинается или заканчивается на жетсткий побел, то оно становится не итерируемым. вот и вся суть

function Class(){

}

Class.extend = function (Prototype) {

    Prototype.prototype = this.prototype;
    constructor.prototype = new Prototype();
    constructor.extend = this.extend;

    
    function constructor() {
        if (this.constructor) {
            this.constructor.apply(this, arguments);
        }

        for (var key in this) if (this.hasOwnProperty(key) && /(^_)|(_$)/.test(key)) {
            Object.defineProperty(this, key, {
                value       : this[key],
                writable    : true,
                configurable: true,
                enumerable  : false
            });
        }
    }


    for (var key in constructor.prototype) if (constructor.prototype.hasOwnProperty(key)) {

        if (/(^_)|(_$)|(constructor)/.test(key)) {
            Object.defineProperty(constructor.prototype, key, {
                value       : constructor.prototype[key],
                writable    : true,
                configurable: true,
                enumerable  : false
            });
        }

        if (key in this.prototype && typeof this.prototype[key] === 'function') {
            Object.defineProperty(constructor.prototype, '$' + key, {
                value       : this.prototype[key],
                writable    : false,
                configurable: false,
                enumerable  : false
            });
        }

    }


    return constructor;
};


//##############################################################


// проверяем суперметоды
alert('проверяем суперметоды')


var Animal = Class.extend(function () {
    this.say = function () {
        alert('Animal');
    }
});


var Cat = Animal.extend(function () {
    this.say = function () {
        this.$say();
        alert('Cat');
    }
});


new Cat().say(); // Animal, Cat



// проверяем приватные
alert('проверяем приватные')

var Animal = Class.extend(function () {
    this.say = function () {

    };

    this._need = function () {

    }
});


for (var key in new Animal) alert(key) // say



// проверяем instanceof
alert('проверяем instanceof')

alert( new Cat() instanceof Cat ) // true

Maxmaxmaximus11 19.03.2014 17:54

Ну а дальше вы можете расширять этот каркас всякими деструкторами и евент эмиттерами:

var EventEmitter = Class.extend(function () {


    this.constructor = function () {
        this._handlersStore = {}
    };


    this.on = function (type, handler) {
        var handlersStore = this._handlersStore;
        var handlers = handlersStore[type] || (handlersStore[type] = []);

        handlers.push(handler);
    };

    this.emit = function (type) {
        var self = this;
        var eventArgs = [].slice.call(arguments, 1);
        var handlersStore = this._handlersStore;
        var handlers = handlersStore[type] || [];

        handlers.forEach(function (handler) {
            handler.apply(self, eventArgs);
        });
    };

});


var q = new EventEmitter();

q.on('click', function () {
    alert('on click!');
});

q.emit('click');

nerv_ 19.03.2014 18:35

1. Если я правильно понял, то это
function constructor() {
    if (this.constructor) {
        this.constructor.apply(this, arguments);
    }
}

правильней написать так
function constructor() {
    if (this.$constructor) this.$constructor.apply(this, arguments);
    if (this.constructor) this.constructor.apply(this, arguments);
}

2. Как быть, если потребуются уникальные функции для экземпляра, а не из прототипа?
3. Если уж так писать циклы, обертки и т.п. то можно и миксыны сделать
4. Нет той гибкости, кот. есть при использовании ссылки на СуперКласс (на мой взгляд)
5. Кроме того, стороннему разработчику придется разбираться в твоей капусте :)

Sweet 19.03.2014 18:44

Цитата:

Сообщение от Maxmaxmaximus11
к суперметодам обращаемся через $methodName

Обрати внимание на название темы. С твоим подходом не получится многоуровневое наследование.


Часовой пояс GMT +3, время: 10:28.