Answer the question
In order to leave comments, you need to log in
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); });
Answer the question
In order to leave comments, you need to log in
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question