Detect unbound native functions like `Array.push`? - javascript

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)

Related

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

Why would you pass 'null' to 'apply' or 'call'?

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.

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

Javascript call and apply functions only called on first argument?

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.

Categories