Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 401
SphynxTech Avatar asked Nov 29 '25 01:11

SphynxTech


2 Answers

try it:

B['function_b'] = A['function_a'];
like image 78
sergioBertolazzo Avatar answered Dec 01 '25 15:12

sergioBertolazzo


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();
like image 25
DontVoteMeDown Avatar answered Dec 01 '25 14:12

DontVoteMeDown