Reputation: 697
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);
Upvotes: 2
Views: 59
Reputation: 5343
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
Upvotes: 0
Reputation: 172518
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);
Upvotes: 1
Reputation: 1074929
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:
Function#call
(in the spec | on MDN)Function#apply
(in the spec | on MDN)this
(on my blog)Upvotes: 2