2

Here is an example of my current code :

var myObject = new Obj();

if(something)
    myObject.method1(arg1, arg2);
else
    myObject.method2(arg1, arg2);

and how I declared my obj :

function Obj() { }

Obj.prototype.method1 = function(a, b) { }
Obj.prototype.method2 = function(a, b) { }

Since i'm doing this kind of test a bunch of time, I was wondering if it was possible to do something like that :

if(something)
    var method = method1;
else
    var method = method2;

myObject.method(arg1, arg2);

3 Answers 3

2

Yes, functions are first-class objects in JavaScript, so you can store function references in variables and then call the function via the variable. In your case, you need to do that in a special way to ensure that this is myObject within the call:

var method;
if(something)
    method = myObject.method1;
else
    method = myObject.method2;

method.call(myObject, arg1, arg2);

Note the use of call there at the end: That allows you to call a function and control what this is within the function call.

If the condition really is that short, you can do this:

var method = something ? myObject.method1 : myObject.method2;
method.call(myObject, arg1, arg2);

Or even:

var method = something ? "method1" : "method2";
myObject[method](arg1, arg2);

More to explore:

Sign up to request clarification or add additional context in comments.

2 Comments

just for curiosity, why did you write method = myObject.method1, it seems a bit redundant since myObject is already mentioned in call(). Wouldn't method = Obj.prototype.method1 make more sense ? But thanks, that's exactly what I wanted ^^
@user1278743: I seem to have missed that question. We may not know that myObject doesn't have a special method1. If it doesn't, then myObject.method1 and Obj.prototype.method1 refer to the same function and the latter is just more typing, but if it does, we'd get the wrong method. :-) It also might not be clear to people reading the code that myObject is backed by Obj.prototype so clarity would suffer.
1

You use a function reference in a variable like this:-

var method;
if(something)
    var method = myObject.method1;
else
    var method = myObject.method2;

method.call(myObject, arg1, arg2);

Comments

0

you can just do:

var method = myObject.method1;

then call it like:

method.call(myObject);

but you can also bind method to an object:

var method = myObject.method1.bind(myObject);

then you can call it normally:

method();

and this inside will be myObject

you can replace bind with simple:

var method = function() { myObject.method1(); }

if you want to support older browsers

Comments

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.