Javascript object which has key as function name and value as function.
var fnObj = { getReport: [Function], getAccountDetail: [Function] }
method invoke using call
fnObj['getReport'].call(null,arg1,arg2); // since its dynamic method call so using call()
or without call()
var a = fnObj['getReport'](arg1,arg2);
dynamic function
getReport:function(arg1,arg2){
//it will do some execution with arg1 and arg2
return {'some': 'result'};
}
Which way of call method invoke is correct?
The only difference between those two methods is the value of this inside the function.
When you explicitly set it to null it will be null (unless you aren't in strict mode, in which case it will be the default object), when you don't it will be the value of fnObj.
Which is correct (assuming that one is not) will depend on what the function does with this (which we can't tell because you haven't shared that code).
Re update:
Since you don't use this in the functions, it doesn't make a difference (except that using call is more long-winded and implies that the value of this matters when a maintainer comes along to read the code).
The normal way would be.
fnObj.getReport(arg1, arg2);
Unless you have specific needs.
Related
In this article js log function, there is a statement:
Function.prototype.apply.call(console.log, console, arguments);
I'm really confused by this statement.
What does it do?
How can I analyse this statement?
Or with some thoughts or tools, I can figure it out step by step?
Can it be simplified to more statements to achieve the same result? for instance: var temp = Function.prototype.call(console.log, console, arguments); Function.prototype.apply(temp);
Thanks for the response.
Apply is a function on the function prototype. Call is also a function on the function prototype. Apply is a function, therefore, it has call on it's prototype. All this is doing is calling the apply function.
Read more about apply here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
What does it do?
It calls console.log with console as this during the call, passing along the arguments in the
pseudo-array arguments as discrete arguments to the function.
So if arguments had "hi", "there" in it, it would be the same as:
console.log("hi", "there");
How can I analyse this statement?
Or with some thoughts or tools, I can figure it out step by step?
Let's start with what the apply and call functions are: They each have the ability to call a function
using a specific this during the call and passing arguments to that function. apply gets those
arguments from a single array (or anything array-like). call gets those arguments as individual arguments.
Normally, you'd see apply or call used like this:
someFunction.apply(valueForThis, ["arg1", "arg2", "arg3"]);
// or
someFunction.call(valueForThis, "arg1", "arg2", "arg3");
The only difference between apply and call is how they expect to get their arguments (apply = in
an array-like thing, call = as individual arguments).
So why, then, isn't that code doing this?
console.log.apply(console, arguments);
It's being cautious: console.log is a function provided by the host. It may not be a true JavaScript
function, and so it may not have the apply property.
So that code is avoiding relying on console.log having the apply property.
Which is where Function.prototype comes in. It's a reference to the object that is the prototype of all true JavaScript functions.
That prototype is where the apply and call properties on JavaScript functions come from.
So if we're worried that console.log doesn't have it (e.g., in case it doesn't inherit from Function.prototype), we can grab apply from that prototype object directly.
So the code is using call to call apply, and using apply to call console.log.
Can it be simplified to more statements to achieve the same result?
Not really, there's not a lot we can separate. I'll try to use variable names to clarify:
var thisValue = console;
var functionToCall = console.log;
var applyFunction = Function.prototype.apply;
applyFunction.call(functionToCall, thisValue, arguments);
Let's take this one part at a time.
Function.prototype.apply, more commonly seen as myBigFatFunction.apply, lets you call a function with a different this context than it would normally have. The difference between apply and call is that the former takes an array of arguments, the latter takes direct arguments after the first. Example:
myStr.substring(5)
String.prototype.substring.apply(myStr, [5]);
String.prototype.substring.call(myStr, 5);
^ all equivalent
However, for reasons I can't fully explain myself, some browser-native functions accessible to JavaScript don't have this function as a property (eg, console.log.apply). It's still possible to manually call it in the same manner though; so that console is still this, when it calls log, and that's what the given function is doing.
The reason for all that complication is that they want to pass in the arguments special variable. This is a keyword that exists in all functions, which represents all arguments to the function as an array-like object (so, suitable for Function.prototype.apply)
Your variable suggestion would likely simply call console.log once with console as argument one, and arguments as variable two, and return the result, rather than give you a function in a variable. If you want a shortened reference, it's possible you could use Function.prototype.bind, but that could actually lengthen your code.
According to this JavaScript reference:
The value null is a JavaScript literal representing null or an "empty"
value, i.e. no object value is present. It is one of JavaScript's
primitive values.
function getMax(arr){
return Math.max.apply(null, arr);
}
Wouldn't explicitly passing the keyword this be clearer, or at least more readable? Then again, at this point I may not understand why you would use null.
Why would you pass 'null' to 'apply' or 'call'?
When there is no value you wish to specify for the this pointer inside the function and the function you're calling is not expecting a particular this value in order to function properly.
Wouldn't explicitly passing the keyword this be clearer? Or at least
more human readable. Then again at this point I may not understand why
you would use null.
In your specific case, probably the best thing to pass is the Math object:
function getMax(arr){
return Math.max.apply(Math, arr);
}
While it turns out that it doesn't matter what you pass as the first argument for Math.max.apply(...) (only because of the implementation specifics of Math.max()), passing Math sets the this pointer to the exact same thing that it would be set to when calling it normally like Math.max(1,2,3) so that is the safest option since you are best simulating a normal call to Math.max().
Why would you pass 'null' to 'apply' or 'call'?
Here are some more details... When using .call() or .apply(), null can be passed when you have no specific value that you want to set the this pointer to and you know that the function you are calling is not expecting this to have any specific value (e.g. it does not use this in its implementation).
Note: Using null with .apply() or .call() is only usually done with functions that are methods for namespace reasons only, not for object-oriented reasons. In other words, the function max() is a method on the Math object only because of namespacing reasons, not because the Math object has instance data that the method .max() needs to access.
If you were doing it this way:
function foo() {
this.multiplier = 1;
}
foo.prototype.setMultiplier = function(val) {
this.multiplier = val;
}
foo.prototype.weightNumbers = function() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += (arguments[i] * this.multiplier);
}
return sum / arguments.length;
}
var x = new foo();
x.setMultiplier(3);
var numbers = [1, 2, 3]
console.log(x.weightNumbers.apply(x, numbers));
When the method you are calling .apply() on needs to access instance data, then you MUST pass the appropriate object as the first argument so that the method has the right this pointer to do its job as expected.
Calling apply with null as the first argument is like calling the function without providing any object for the this.
What does the apply method do?
The apply() method calls a function with a given this value and
arguments provided as an array (or an array-like object).
fun.apply(thisArg, [argsArray])
thisArg
The value of this provided for the call to fun. Note that this may not
be the actual value seen by the method: if the method is a function in
non-strict mode code, null and undefined will be replaced with the
global object, and primitive values will be boxed.
Further documentation can be found here.
One case where I have found this useful is when the function I'm calling is already bound to a particular context.
Because bound functions cannot be rebound, and they will always be called with the thisArg that was passed into bind, there is no use in passing a thisArg into call or apply. From source:
The bind() function creates a new bound function (BF).... When bound function is called, it calls internal method [[Call]] on [[BoundTargetFunction]], with following arguments Call(boundThis, args).
Here's an example:
class C {
constructor() {
this.a = 1;
}
}
function f(n, m) {
console.log(this.a + n + m);
}
let c = new C();
var boundF = f.bind(c, 2); // the context `c` is now bound to f
boundF.apply(null, [3]); // no reason to supply any context, since we know it's going to be `c`
I am bit late to answer this. I will try to give a long descriptive explanation here.
What is null in JavaScript?
The value null is a literal (not a property of the global object like undefined can be). It is one of JavaScript's primitive values.
In APIs, null is often retrieved in place where an object can be expected but no object is relevant.
fun.apply(thisArg, [argsArray])
thisArg: The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.
argsArray: An array-like object, specifying the arguments with which fun should be called, or null or undefined if no arguments should be provided to the function. Starting with ECMAScript 5 these arguments can be a generic array-like object instead of an array. See below for browser compatibility information.
If you are using 'strict mode', then it is advisable to pass the this or
Math as the parameter.
Apply is useful when you want to pass along the responsibility for doing something to a function that is determined at run time, and pass a variable number of arguments to that function. You may or may not have any appropriate "this" context when you're doing that.
For example I use a library I wrote to facilitate listening for and raising application events that uses apply.
I wanted to be able to be able to raise an event like this:
EventManager.raise('some:event-name', arg1, arg2, arg3, ..);
..and have all of the registered handlers for that event get called with that list of arguments (arg1, arg2, etc). So in the raise function, it goes through the handlers that are registered for that event name and calls them, passing all the passed in arguments except for the event name, like this:
var args = [];
Array.prototype.push.apply(args, arguments);
args.shift();
for (var l in listeners) {
var listener = listeners[l];
listener.callback.apply(listener.context, args);
}
When a registered handler (listener.callback) is called, apply is used to pass along a variable number of arguments. Here I have allowed the listener to supply a this context for its event handler when the listener is defined, but that context might not be defined or it might be null, and that's perfectly fine.
For a long time the raise function didn't even facilitate using any callback context. I eventually came across a need for it, so I put in support for it, but most of the time I don't really need or use it.
I'm reading Nicholas Z.Zakas' Professional JavaScript for web developer 3rd edition and inside the Reference types chapter I got a bit confused at the function type part.
function sum(num1, num2){
return num1 + num2;
}
function callSum1(num1, num2){
return sum.apply(this, arguments);
}
alert(callSum1(10,10)); //20
He says:
"In this example, callSum1() executes the sum() method, passing in this as the this value (which is equal to window because it's being called in the global scope) and also passing in the arguments object."
I understand what he says, but I don't understand the why. This supposed to point to the function doesn't it? Now I'm confused that it's pointing to the window because it's being called in the global scope ..
Can someone be kind to explain it to me? :)
I'm not sure if I will or I have to use this technique later, but I want to make sure I understand it, especially the this part. More details about this and its usage will come in the OOP section, but it's now an interesting question.
Thanks in advance!
The value of this depends on how you call a function.
If you call a function using call or apply then the value of this will be the first argument to that function.
Here you have sum.apply(this, arguments); so it will pass the current value through. As usual, that value is determined by how you call the function.
Since you call callSum1(10,10) with no context, this will be window.
(If you were in strict mode, it would be undefined. If you weren't in a browser, it would be whatever the default object of the JS environment you were using was).
Here:
alert(callSum1(10,10)); //20
...you're calling callSum without doing anything to set this during the call, and so this is defaulted to the global object (window, on browsers). (In loose mode; in strict mode, this would have been undefined.)
Since you're then using apply and passing that same this into it:
return sum.apply(this, arguments);
...naturally the global object is also used when calling sum.
I understand what he says, but I don't understand the why. This supposed to point to the function doesn't it?
No, this almost never refers to functions. (It can, of course, it just very rarely does.)
Now I'm confused that it's pointing to the window because it's being called in the global scope ..
It's not because it's being called in the global scope; it would be the same if it were being called from inside a function. What matters isn't where the call occurs, but how. Any time you call a function without doing anything to set this, in loose mode, this during the function call will be the global object. It doesn't have to be at global scope; what matters is how you call the function.
The rule is actually a lot simpler than people make it out to be: If you call a function without doing anything to set this, during the call, this will be the global object (in loose mode) or undefined (in strict mode). Here are the things you can do to set this during a function call:
Call the function as part of an expression getting the function from a property on an object. For example, foo.bar(); retrieves a reference to the function from the bar property on foo, then calls bar. Because we did it that way, during the call to bar, this refers to foo.
Call the function using .call or .apply; this will be what you pass in the first argument. (In loose mode, if you pass undefined, null, or a non-object in the first argument, during the call this will be the global object. In strict mode, it'll be what you pass.)
Call a bound function. That's a function created via Function#bind (an ES5 feature). Bound functions have this "baked into" them.
More (on my blog):
Mythical methods
You must remember this
Under the Window object part ~20 pages later, I'm reading this: "As mentioned previously, the this value is equivalent to the Global object when a function is executed with no explicit this value specified (either by being an object method or via call()/apply())." :)
Maybe I didn't get it before, but now it's clear with his words as well. By the way, the book is awesome! Now with Math object I can understand much more the apply() method, too.
var values = [1,2,3,4,5,6];
var max = Math.max.apply(Math, values);
I've seen it done differently in code out there, but is there any benefit or reason to doing a (blank params) .call / .apply over a regular () function execution.
This of course is an over-simplified example
var func = function () { /* do whatever */ };
func.call();
func.apply();
VERSUS just the simple parenthesis.
func();
Haven't seen any information on this anywhere, I know why call/apply are used when params are passed.
When you call a method with func();, this variable inside the method points to window object.
Where as when you use call(...)/apply(...) the first parameter passed to the method call becomes this inside the method. If you are not passing any arguments/pass null or undefined then this will become global object in non strict mode.
Yes, there is an important difference in some cases. For example, dealing with callbacks. Let's assume you have a class with constructor that accepts callback parameter and stores it under this.callback. Later, when this callback is invoked via this.callback(), suddenly the foreign code gets the reference to your object via this. It is not always desirable, and it is better/safer to use this.callback.call() in such case.
That way, the foreign code will get undefined as this and won't try to modify your object by accident. And properly written callback won't be affected by this usage of call() anyways, since they would supply the callback defined as an arrow function or as bound function (via .bind()). In both such cases, the callback will have its own, proper this, unaffected by call(), since arrow and bound functions just ignore the value, set by apply()/call().
I know PHP has call_user_func, I was just wondering if JavaScript had something similar, where the method I want to call is, for example: object.set$fieldID($fieldValue)
I would rather not go through if/else/switch blocks just to execute one line of code properly.
If it helps, I am using jQuery.
object["set" + $fieldID]($fieldValue);
Some reading material for the above: Member Operators on MDC.
Some advanced methods include Function.prototype.call and Function.prototype.apply. The first is somehow equivalent to PHP's call_user_func() while the latter is somehow equivalent to PHP's call_user_func_array().
The difference between PHP's functions and JavaScript's is that JavaScript allows you to call methods of some object in the context of another object. This is done through the use of the first argument of call() and apply().
An equivalent for the above example, but using call() and apply() looks like this:
object["set" + $fieldID].call(object, $fieldValue);
object["set" + $fieldID].apply(object, [$fieldValue]);
The first argument must be object otherwise the method will be executed with the this pointer bound to the global object, window in the case of browsers.
#lonut is correct. More generally though, if you want to call functions that aren't a part of an explicit object (e.g.: global), you can call them on the window object:
var foo = function() { alert(1); };
window['foo']();
since all objects are contained in window.
Another example:
var object = function() { this.method = function() { alert(2); }; }
var instance = new object();
window['instance']['method']();