Javascript call and apply functions only called on first argument? - javascript

Edit: this question was asked due to my misunderstanding. Proceed with caution, as reading it might waste your time.
I thought call and apply would execute a function given a set of arguments, but I'm getting confusing test results. See my test code:
window.z = 0;
(function(){++(window.z)}).call(this, 1, 2, 3)
I would expect z to be 3 after execution. However, z is 1.
(function(){++(window.z)}).apply(this, [1, 2, 3])
Same here. z == 1;
I tried simply logging the input argument as well:
var x = function(y){console.log(y);}
x.call(this, 1, 2, 3);
Result? Only 1 is logged.
What am I doing wrong here?
(Tested in Chrome and Firefox with Firebug.)

Both call and apply only call the function once. The difference is how the arguments to the invocation are passed.
With call, each parameter after the context (first parameter), is a parameter. With apply, the second parameter should be an array like object of parameters (the first parameter still provides the context).
function foo(a, b, c) {
};
foo.call(this, 1, 2, 3); // a == 1, b == 2, c == 3;
foo.apply(this, [1,2,3]); // a == 1, b == 2, c == 3;
If you want to call the function multiple times, you can accomplish this by simply putting the call in a loop.

It seems that you are under the impression that the call and apply methods should call the functon once for each parameter. That is not the case, it only calls the function once.
The apply methods takes an array of arguments:
func.apply(this, [1, 2, 3]);
The call methods takes an argument list:
func.call(this, 1, 2, 3);

This is expected, the arguments you pass will be present in your increment function (as arguments see here for reference), but you are only calling the function once.

Related

`arguments` used in inner function/arraow function behave differently [duplicate]

(() => console.log(arguments))(1,2,3);
// Chrome, FF, Node give "1,2,3"
// Babel gives "arguments is not defined" from parent scope
According to Babel (and from what I can tell initial TC39 recommendations), that is "invalid" as arrow functions should be using their parent scope for arguments. The only info I've been able to find that contradicts this is a single comment saying this was rejected by TC39, but I can't find anything to back this up.
Just looking for official docs here.
Chrome, FF, and node seem to be wrong here, Babel is correct:
Arrow functions do not have an own arguments binding in their scope; no arguments object is created when calling them.
looking for official docs here
Arrow function expressions evaluate to functions that have their [[ThisMode]] set to lexical, and when such are called the declaration instantiation does not create an arguments object. There is even a specifc note (18 a) stating that "Arrow functions never have an arguments objects.".
As noted by Bergi, arrow functions do not have their own arguments variable.
However, if you do want to capture the args for your arrow function, you can simply use a rest parameter
const myFunc = (...args) =>
console.log ("arguments", args)
myFunc (1, 2, 3)
// arguments [1, 2, 3]
Rest parameters can be combined with other positional parameters, but must always be included as the last parameter
const myFunc = (a, b, c, ...rest) =>
console.log (a, b, c, rest)
myFunc (1, 2, 3, 4, 5, 6, 7)
// 1 2 3 [ 4, 5, 6, 7 ]
If you make the mistake of writing a rest parameter in any other position, you will get an Error
const myFunc = (...rest, a, b, c) =>
console.log (a, b, c, rest)
myFunc (1, 2, 3, 4, 5, 6, 7)
// Error: Rest parameter must be last formal parameter

window.onblur and console.log partial application with bind

I was reading through some javascript posts, and I came across this answer.
Basically, in the answer, the poster said that you could set
window.onblur = myBlurFunction
only if myBlurFunction is a function that doesn't need any arguments passed to it.
I was about to comment that it was possible to use bind to perform partial application for functions requiring arguments, but when I tried
var myBlurFunction = console.log.bind(console,'blur');
window.onblur = myBlurFunction;
blurring the window didn't print the string "blur", but instead printed what seems to be a blur object
blur blur { target: Window → window-onblur-not-working, …
Does anyone know why this approach doesn't work?
What I'm really looking for with my question is why is the event handler function given the event as an argument?
window.onblur = function(event){console.log(event)}
I've never seen any documentation that mentions or explains the event parameter.
Also, how is the bound parameter overridden? Typically once a value is bound to a function parameter, any additional arguments will be assigned to the subsequent parameters:
var f = function(arg1,arg2){console.log(arg1,arg2)};
g = f.bind(null,1);
g(); // 1 undefined
g(2); // 1 2
g.call(null,2); // 1 2
Quoting the bind() page on MDN:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Let's split those two concepts and then explain them together in your example.
Changing the this context
This is an adaptation of the example in the MDN page (I promise it's simple!):
// This assignment is equivalent to 'window.x' or 'var x' in the global scope
this.x = "global!";
var obj = {
x: "not global!",
getX: function() {
return this.x;
}
};
// Running inside the object's scope, returns obj.x
obj.getX();
//=> "not global!"
// Assign the scoped function (obj.getX) to a global variable
var retrieveX = obj.getX;
// Running in the global scope, returns window.x
retrieveX();
//=> "global!"
// Binds the 'retrieveX' function to run inside the object's scope
var boundedRetrieveX = retrieveX.bind(obj);
// Running inside the specified 'obj' scope, returns obj.x
boundedRetrieveX();
//=> "not global!"
From that, we gather that passing obj as an argument changes what context this refers to.
On your example, you're doing something like this:
console.log.bind(console); // The second argument doesn't matter for now
So you're telling console.log that any instances of this are a reference to the console context. Which I suppose is fine, shouldn't do much damage.
Prepending arguments
Again, adapting from the MDN page example:
function list() {
// Simply convers the arguments list into an Array, then returns it
return Array.prototype.slice.call(arguments);
}
// Example usage
list(1, 2, 3);
//=> [1, 2, 3]
// Using 'bind' to prepend to (append to the start of) the arguments list
// Note that, because 'this' context doesn't matter, the first argument is null
var betterList = list.bind(null, 98);
// Passing no arguments, it returns an array with only 98
// This is similar to '[98].concat([])'
betterList();
//=> [98]
// Passing arguments, it appends 98 to the start of the array
// Again, this is similar to '[98].concat([1,2,3])'
betterList(1, 2, 3);
// [98, 1, 2, 3]
// The parameters can go on indefinitely. They will all be added to the start of the arguments list in order
var bestList = list.bind(null, 98, 99, 100);
bestList(1, 2, 3);
//=> [98, 99, 100, 1, 2, 3]
The function list turns the Array-like object arguments, which contains all of the arguments passed to the function, into an actual Array.
With bind(), we append values to the start of that argument list, so that to the function, it seems as if they were already passed in that way in the first place.
Your code looks something like this:
console.log.bind(console, "blur");
Ignoring the first argument, you're prepending the arguments sent to console.log (which in this case is the event response) with "blur". Which also isn't harmful, just not very useful.
Final thoughts
So, here's a screenshot of me playing around with the arguments. The first argument, that indicates the context for this, is set to null, just like in the example above, because it doesn't actually matter here. And I've passed a long list of arguments afterwards to be prepended to the onblur event response.
As you can see, even though I added a bunch of stuff to the response, the Event object (not a blur object! haha) is still there.
So that is why it "doesn't" work. It works in its own way. That just might not be what you were expecting.
You can still go for approaches presented in the question you linked, such as
window.onblur = () => console.log("blur");
Solutions that are less complicated and actually do what you expect them to

Does JavaScript `arguments` contain `this`?

I'm trying to understand JavaScript's arguments implicit variable in functions. Some tutorials delete the 0th element of it and say that it contains this but some other tutorials don't delete the 0th element. I'm very confused.
I wrote this code example and it shows that arguments doesn't contain this:
function aaa () {
console.log(arguments[0])
}
aaa(1,2,3);
Is it possible that sometimes arguments contains this? I wonder why some tutorials slice away the 0th element before using arguments.
most likely you have a function like blah(x) In which case you take off the first argument because it is already captured as the variable x, and you want the rest of the arguments that have been passed in.
The first argument is not this.
Arguments is an array* of the original arguments passed into the function, and doesn't directly have anything to do with the "this" variable.
That said, different tutorials probably try to explain how function references work, etc, using the scope (scope => "this" variable) of the function. This could easily involve passing an array and shifting off the first argument.
Consider this simple snippet:
var sample = function(a,b,c){
console.log(arguments, this);
};
sample(1,2,3);
Outputs:
[1, 2, 3], window
As we know by now, "this" is a special variable that has to do with the scope of the function. There are plenty of articles describing what it does/how it works, but in this context specifically, you've probably seen things used in a manner with .call or .apply:
sample.call(sample, 1, 2, 3)
or
sample.apply(sample, [1,2,3])
Those snippets both do the same thing - they convert the "this" scope of the function from the window object (since "sample" was declared as a global function) to the "sample" function itself, and pass the parameters 1, 2 and 3. They output:
[1, 2, 3], [sample function]
The reason some tutorials will shift off the first argument in this context is that there are often "helper" functions to make it more obvious when scope is changed, and many times those helper functions take, as their first parameter, the scope in which the new function is to be executed. So, they shift off the first parameter, and use that when (essentially) calling apply. A common example is bind(), like so:
Function.prototype.bind = function(scope){
var me = this,
args = Array.prototype.slice.apply(arguments, [1]);
return function () {
var handlerArgs = [];
for (i = 0; i < args.length; i++) {
handlerArgs.push(args[i]);
}
for (var i = 0; i < arguments.length; i++) {
handlerArgs.push(arguments[i]);
}
me.apply(scope, handlerArgs);
};
};
Now, you can call:
var bound = sample.bind(sample, 1);
bound(2,3);
...and get the output:
[1, 2, 3] [sample function]
You can see we're passing some parameters (the scope and the first parameter) when we bind the function initially, at which point we slice off the first argument ("sample", because that's the "scope" and has to be handled differently than any other arguments), then later, when bound() is invoked, push the 1, as well as 2 and 3, into the final arguments list.
It's a bit confusing at first, but hopefully that helps a little.
*Technically array-like.

How do I use the "arguments" key on the function object?

If I type this and check it out in my Chrome console:
function f(){}
console.dir(f);
What is displayed are these keys:
> arguments
> caller
> length
> name
> prototype
> __proto__
Now, I'm curious if the arguments key on the constructor function is there to aid me in some way visually to see the arguments that are passed to a function, but everytime I pass an argument to a function it fires it off automatically:
function f(a){alert(a)}
console.dir(f("test"));
So, it seems quite useless as an analytic tool. Is this key just here to temporarily hold the arguments and nothing more just for the sake of passing arguments? Or is there something else to this key? I'm sure this is probably a dumb question but I'm curious.
The arguments object is a local variable available within all functions.
You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function.
if a function is passed three arguments, you can refer to the argument as follows:
arguments[0]
arguments[1]
arguments[2]
Reference link arguments.
arguments is an array like object that is available in function objects in javascript. It allows a function a way to account for arguments that were used while invoking a function but do not have a parameter specifically assigned to it.
var mul = function ( ) {
var i, total = 0;
for (i = 0; i < arguments.length; i += 1) {
total *= arguments[i];
}
return total;
};
document.writeln(mul(4, 8, 2)); //64
Source: http://goo.gl/hKpFGl
This explanation is pretty much ripped directly from here. If you want to get familiar with some good patterns javascript offers this isn't a bad place to start.
arguments is an Array-like object corresponding to the parameters passed to a function.
For Example:
function callMe (a, b, c){
console.log(arguments);
}
callMe(); // return empty array []
callMe(1,2); // return array [1, 2]
callMe(1,2,3); // return empty array [1, 2, 3]
callMe(1,2,3,4); // return empty array [1, 2, 3, 4]
For more help, read this doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments

Detect unbound native functions like `Array.push`?

Observe the following:
function array_map(array, callback) {
for (var i = 0; i < array.length; i += 1) {
callback(array[i]);
}
}
var a = [], b = [];
array_map([1, 2, 3], function (x) { a.push(x); });
// just gives a = [1, 2, 3] as expected
// but why does this not work: ?
array_map([1, 2, 3], b.push);
// Chrome: a = [], Firefox: can't convert undefined to object
I do understand why this happens, namely: push is no longer bound to b (but to the global object) if you pass it to array_map directly. I don't really understand why Chrome doesn't give an error, at least Firefox seems to give some kind of error.
How can I detect if a function like this is passed to array_map to avoid these kinds of bugs?
I'm hoping there are advanced reflection techniques available to trace the origin of a function. For instance b.push.constructor gives Function, but that's not what I'm looking for.
I'm not sure what you expect there to happen. Array.prototype.map requires a function as second parameter, which returns a new value for every iteration.
Passing in just a function reference (which you do in your second example) doesn't tell the function what it has to do anyway. So you're kinda expecting that .map() applies some black magic and calls the passed in method with the correct parameter, which it obviously, can't do.
I totally didn't get that you wrote your own mapping function. However, your problem there is that you're losing scope of that .push() function. Only if you call it on the Array / Object like xxx.push(), the this within the called function will correctly reference the target object. Once you just passed the reference, this will either point to global / window or undefined and won't work anymore.
So solve that issue you could call it like
array_map([1, 2, 3], b.push.bind(b));
which also would apply an ES5 function. You can't really detect for it within the array_map(). A function is a function, your best shot would be to detect whether or not the passed in method is a native or not, but I wouldn't recommend that.
Usually these sorts of functions would allow you to set the context of the callback.
If you change your array_map function to accept a context, then it will work like this.
function array_map(array, callback, context) {
for (var i = 0; i < array.length; i += 1) {
callback.call(context, array[i]);
}
}
var b = [];
// now the push method is called from the b context
array_map([1, 2, 3], b.push, b);
The problem is, that Javascript has no such thing like "methods" - a function exclusively bound to a certain object. In your first example you pass a function which invokes a.push. this is bound to a here because you invoke it directly on a.
In your second code you just pass the function push without the context of b - this will be bound to the execution context which is the gloabl object.
You need to bind the the context of the function like the following:
array_map([1, 2, 3], b.push.bind(b));
or jQuery's proxy(). I can't find another simple solution at the moment but the one to hand over the context directly in a third parameter: function array_map(array, callback, context)

Categories