Clone or copy a method in an object (Javascript) - Stack Overflow

Suppose I have an object A:var A = {'parameter': "Dura lex sed lex.",'functio

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?

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?

Share Improve this question edited May 26, 2021 at 5:38 SphynxTech asked Jun 12, 2017 at 18:55 SphynxTechSphynxTech 1,8492 gold badges20 silver badges40 bronze badges 4
  • _proto ? property. – Arpit Solanki Commented Jun 12, 2017 at 18:57
  • @ArpitSolanki No – Bergi Commented Jun 12, 2017 at 19:01
  • 1 Just assign B.function_b = A.function_a;? – Bergi Commented Jun 12, 2017 at 19:01
  • 1 "Vini vidi vici!" is not what Caesar said... It's "veni" :) – PeterMader Commented Jun 12, 2017 at 19:13
Add a ment  | 

3 Answers 3

Reset to default 3

try it:

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

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();

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!');
};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745474100a4629266.html

相关推荐

  • Clone or copy a method in an object (Javascript) - Stack Overflow

    Suppose I have an object A:var A = {'parameter': "Dura lex sed lex.",'functio

    2小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信