SphynxTech
SphynxTech

Reputation: 1849

Clone or copy a method in an object (Javascript)

Suppose I have an object A:

var A = {
    'parameter': "Dura lex sed lex.",
    'function_a': function (new_type) {
        console.log ("It's working!");
    }
};

Then, suppose I also an object B:

var B = {
    'parameter': "Veni vidi vici!"
};

What I need is a simple way to dynamically create a method function_b() inside the object B without copy/clone the parameter, of the object A, ("Dura lex sed lex.") in the object B and to preserve the parameter ("Veni vidi vici!") of the object B.

How can I do it?

Upvotes: 3

Views: 3085

Answers (3)

I don't know if I understood your question, but I think you want something like this:

B.function_b = function(whatever) {
  console.log('it works!');
};

Upvotes: 1

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

You mean something like this?

var A = {
    'parameter': "Dura lex sed lex.",
    'function_a': function (new_type) {
        console.log ("It's working!");
    }
};

var B = {
    'parameter': "Vini vidi vici!"
};

var clone = function(origin, target, prefix) {
  Object.keys(origin).forEach(function(key) {
    if (!target.hasOwnProperty(key)) {
      if (key.indexOf("function_") > -1) {
        target["function_" + prefix] = origin[key];
      }
    }
  });
}

clone(A, B, "b");

console.log(B);
B.function_b();

Upvotes: 2

sergioBertolazzo
sergioBertolazzo

Reputation: 604

try it:

B['function_b'] = A['function_a'];

Upvotes: 3

Related Questions