1

i have a object in javascript and some already defined functions. but how can i assign those functions to the object attributes. i tried different ways. but no hope.. the snippet is given below

// object
var func = {
 a : '',
 b : ''
};

// methods
var test1 = function(i) { console.log(i); }
var test2 = function(i) { console.log(i*100); }

i need to assign the test1 to a and test2 to b. i tried like this.

var func = {
 a : test1(i),
 b : test2(i)
};

obviously the errors i not defined is throwing.. is ther any solution other than the below give sinppet.

var func = {
 a : function(i) { test1(i); },
 b : function(i) { test2(i); }
};

1 Answer 1

3

This does what you're asking:

var test1 = function(i) { console.log(i); }
var test2 = function(i) { console.log(i*100); }
var func = {
  a: test1,
  b: test2
}

But isn't very good style.

This might be better:

function exampleClass () {}
exampleClass.prototype.a = function(i) { console.log(i); };
exampleClass.prototype.b = function(i) { console.log(i*100); };

var exampleObject = new exampleClass();
Sign up to request clarification or add additional context in comments.

4 Comments

is their any other proper way.. rather than this var func = { a : function(i) { test1(i); }, b : function(i) { test2(i); } };
It's not clear what you want the final object to contain: should it be an object with methods called 'a' and 'b', or should it contain two keys whose values are the result of calling those functions?
this is just for a test purpose, to check is it possible to assign a already written method (eg:test(i)) to a object property(func.a) and call it like func.a(10)
Yes, absolutely possible to do "monkey patching" like this. The functions you add might not have access to local variables defined in the constructor however (the usual pattern for so called "private" attributes).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.