3

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?

4
  • _proto ? property. Commented Jun 12, 2017 at 18:57
  • @ArpitSolanki No Commented Jun 12, 2017 at 19:01
  • 1
    Just assign B.function_b = A.function_a;? Commented Jun 12, 2017 at 19:01
  • 1
    "Vini vidi vici!" is not what Caesar said... It's "veni" :) Commented Jun 12, 2017 at 19:13

3 Answers 3

3

try it:

B['function_b'] = A['function_a']; 
Sign up to request clarification or add additional context in comments.

1 Comment

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
2

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

6 Comments

Much too complicated. And that hasOwnProperty check is good for nothing.
@Bergi I supose OP wants a dynamic function, not a hard code snippet.
@Bergi also, he wants to preserve the duplicated keys, that is why I added hasOwnProperty.
We don't know. Better post a comment to ask for clarification instead of a guess at an answer.
Is it possible to do the same thing easier and more quickly?
|
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.