A
A
Artyom Zubkov2014-03-29 09:14:50
JavaScript
Artyom Zubkov, 2014-03-29 09:14:50

How to organize the inheritance of properties by an object of another object with the possibility of simultaneously changing the value of both (JavaScript)?

Faced with a problem. We need to create a number of objects that have a common behavior, in my case it is a get method , but also each has a bunch of other properties, based on which this method should work. Here is my code that turned out to solve the problem:

(function(obj) {
    function Request(action, params) {

        var that = this;

        for (var key in params) {
            if (params.hasOwnProperty(key))
                that[key] = params[key];
        }

        function updateParams() {
            for (var key in params) {
                if (params.hasOwnProperty(key) && that.hasOwnProperty(key))
                    params[key] = that[key];
            }
        }

        this.get = function(callback) {
            updateParams();
            action(params, callback);
        };
    }

    obj.RequestSomething = function() {
        return new Request(controller.selectSomethings, {
            key:  "",
            key1:  "",
            key2:  "defaultValue"
        });
    };

    obj.RequestCircle = function() {
        return new Request(controller.selectCircles, {
            radius:  0,
            x:  0,
            y:  0
        });
    };
})(testObj || testObj = {});

var rq = testObj.RequestSomethings();
rq.key1 = "test";
rq.get(function() { console.log(arguments); });

My question is what is the right way to implement this, using prototype or whatever is generally accepted. That is, it is necessary that the objects have a common interface, but each has its own implementation.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene Obrezkov, 2014-03-29
@ghaiklor

You need to look towards inheritance patterns, if I understand the question correctly. They allow you to define one object with a prototype and then create other objects with prototypes, extending the attributes and prototype of the first one.

V
VoidVolker, 2014-03-29
@VoidVolker

shamansir.github.io/JavaScript-Garden/#function.co...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question