Different functions - are they the same?

I am a little more than a beginner.

While reading the EventEmitter source , I came across this interesting and, to me, elegant function:

// alias a method while keeping the correct context function alias(name) { return function aliasClosure() { return this[name].apply(this, arguments); }; } 

I have two main questions:

First : why is the aliasClosure function named? Is it useful for anything but clarity? Also, is this a closure? For me, this looks like a semi-anonymous function.

Second : I rewrote this function as follows:

 function alias2(name) { return this[name].bind(this); } 

Is it equivalent? I think this should, since the this context is the same, and it persists in both versions.

Is there a reason to prefer one over the other?

+4
source share
2 answers

Providing a name in the expression for the function instance makes the name available for stack tracing. (I am told that new debuggers do not always need it if the function is created in certain contexts, such as var initialization.)

I think the second is equivalent, basically, although .bind() has some obscure special cases that it handles.

change wait - no, they are not equivalent. The first includes this explicitly and searches for each call. The first function does not need this bind to everything when it calls, while yours will throw an exception in this case.

One change that would make the two functions almost equal is a wrapping bind inside a closure, for example:

 function alias2(name) { return function() { return this[name].bind(this); } } 

However, bind is unclear in rare cases.

+1
source

No, this is not at all equivalent. From a look at the alias() function, I think you would use it something like this:

 > Array.prototype.strjoin = alias('join'); // make 'strjoin' an alias of 'join' > [1, 2, 3].strjoin(" + "); "1 + 2 + 3" 

Using alias2() in the above code will not work.

+2
source

Source: https://habr.com/ru/post/1499246/


All Articles