A
A
Andrey2016-06-09 12:01:13
JavaScript
Andrey, 2016-06-09 12:01:13

How to properly create a function that creates classes?

There is such an idea: to create components (classes) with a specific function. This is how the class creation interface should look like:

Component.create('ComponentName', {
init: function () {}
..... и прочие методы
});

For this I created a function:
Component.create = function (name, methods) {

var NewClass = function (/*arguments*/) {
// тут записываем в свойства класса переданные при создании экземпляра аргументы и инициализируем:
this.init();
};

// В прототип новой функции записываем 
// свойства объекта Component, переданные методы и имя класса
// (просто свойство для наглядности):
NewClass.prototype = Object.create($.extend(this, methods, {
            componentName: name
        }));

// А затем сохраняем ссылку на функцию в некоем объекте obj = {}, который находится снаружи:
obj[name] = NewClass;

return NewClass;
};

After that, if you create a couple of classes and look into the obj object, then there will be two functions with the same prototype. This is understandable: I write some data to the NewClass prototype, then, when creating another class, I overwrite the prototype... The NewClass functions are different, but they have the same object-prototype and the properties turned out to be common.
This is not at all what I expected.
How can I make NewClass be a new function each time with its own prototype, which will not be overwritten when Component.create is called again?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kravchenko, 2016-06-09
@f-end

try this

NewClass.prototype = Object.create($.extend({}, this, methods, {
    componentName: name
}));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question