Function closures - javascript

Hi I'm trying to run the following function:
function add (a, b) {
return a + b;
}
var make_lazy = function (add, a, b) {
return function () {
add(a,b);
}
}
Basically what I'm trying to do is to pass another function as an argument and its parameters to the make_lazy function - and then run the function that was passed in as the argument along with the other two parameters. I get undefined is not function as an error when I try to run the code.

You forgot the return statement in the anonymous function that you're returning from make_lazy:
var make_lazy = function (add, a, b) {
return function () {
return add(a,b) // <----- here
}
}

I think you are trying for something like this.
function add (a, b) {
return a + b;
}
var make_lazy = function (a, b) {
return function () {
return add(a,b);
}
}
Then you can call var lazy = make_lazy(3,5); and later call lazy() to get 8

Wrap you lazy function body inside a self calling function and return.
function add (a, b) {
return a + b;
}
var make_lazy = function (add, a, b) {
return (function () {
add(a,b);
})();
}

Here's my point of view.
When you assign a function to make_lazy variable, after that you should make an invocation make_lazy() with the same params as they were in the definition of that function:
make_lazy(function expression, a, b);
This portion:
function (add, a, b)
just makes add a local variable, this is not the same as add(a,b) which is defined above.
To make the code work, try to invoke make_lazy as
make_lazy(add, 3, 4)

Related

Returning a function with the arguments reversed

The code that I am practicing with is where I have a function called InReverse. This function accepts a function as an argument and returns a function. When the function returned is invoked, it reverses the order of the arguments.
When the returned functions are returned:
const catDog = ('cat', 'dog') => returns ('dog cat')
What I have rewritten out so far is:
function inReverse (func) {
return function (...arguments) {
return arguments.map((element) => {
element.reverse();
});
}
}
Any guidance would be appreciated!
You need to simply call the input function inside the newly created anonymous function.
For example this works:
function inReverse(f) {
return function () {
let args = [...arguments].reverse();
return f.apply(this, args);
}
}
So for example if you have subtract function like this:
function subtract(a, b) {
return a-b;
}
subtract(1, 10); will be -9 as expected.
and inReverse(subtract)(1, 10) will be 9 as expected.
Not sure why you're using map, just call reverse right on the arguments array. Also you weren't calling func:
function inReverse(func) {
return function(...args) {
return func(...args.reverse());
};
}
(Notice that arguments is a reserved identifier in strict mode, you should name your parameter for something else)
Not sure, why you are using map method, just use reverse method in your function right on the arguments. Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse?retiredLocale=id
Just reverse the arguments, and use func.apply(this, arr)
function inReverse(func) {
return function() {
var args = Array.prototype.slice.call(arguments)
args = args.reverse();
return func.apply(this, args);
}
}
function div(a, b) {
return a / b
}
console.log(div(1, 2))
console.log(inReverse(div)(1, 2))

What does "a.call.apply(a.bind, arguments)" mean?

Just because of curiosity I wanted to make a bounded function with this particular approach :
var fn = function(a, b, c) {
return a.call.apply(a.bind, arguments)
}
var boundFn = function(a, b, c) {
fn.apply(null, arguments)
}
function unboundedFn() {
console.log(this, arguments)
}
var boundedFn = boundFn(unboundedFn, x, y);
So I'm trying to understand what a.call.apply(a.bind, arguments) do exactly ?
If You have a function like this:
function unboundedFn() {
console.log(this, arguments)
}
You can use unboundedFn.call(thisObj, arg1, arg2) or unboundedFn.apply(thisObj, [arg1, arg2]) to run it, but changing what this means inside. Both call and apply do the same, and only difference is way of passing arguments.
Becouse call, apply and also bind are methods, you can run for example unboundedFn.call.call.call.call.apply.apply.apply.apply(), but it doesn't seem to have to much sense.
In your example return a.call.apply(a.bind, arguments) is equal to return a.bind.call(...arguments), which is equal to a.bind(...arguments.slice(1)), so whole fn function can be simplified to:
function fn(a,b,...args){
return a.bind(b, ...args);
}

Calling function on function result like jQuery does

I am trying to build two functions to work like jQuery functions work, for example: jQuery( 'select').val();
This works:
function func(a) {
console.log(1);
return a;
}
func.sub = function(n) {
console.log(2);
}
func.sub(2);
But this doesn't:
function func(a) {
console.log(1);
return a;
}
func.sub = function(n) {
console.log(2);
//return func result[n];
}
func([1,2,3]).sub(2);
How can I make this second code work and read func() result on sub()?
You need to have func return an object that has a method sub.
function Subbable(x) {
this.value = x;
}
Subbable.prototype.sub = function(b) {
return this.value - b;
}
function func(a) {
return new Subbable(a);
}
func(10).sub(2)
// 8
jQuery's $(...) typically returns a jQuery object that contains a collection of the selected nodes, and whose prototype has all the nice goodies like .attr and .css.

Is this a functional declaration, expression, and object?

I'm learning JavaScript and am trying to learn the proper terms for what I am doing. There are so many ways to create a function.
I have created 3 examples that do the same thing, but the functions are created in completely different ways.
My questions are:
Are any one of these methods better than the other?
Why would I choose to do one way or another?
What is the last "object" method called?
What advice would you have to make this example better?
//EXAMPLE 1
// is this called function declaration?
function add( a, b ) {
return a + b;
}
function subtract( a, b ) {
return a - b;
}
function compute( a, b ) {
var sum = add( a, b );
var difference = subtract( a, b );
var total = sum + difference;
return total;
}
compute( 2, 3 ); //returns 4
//EXAMPLE 2
// is this called function expressions?
var add = function ( a, b ) {
return a + b;
};
var subtract = function ( a, b ) {
return a - b;
};
var compute = function ( a, b ) {
var sum = add( a, b );
var difference = subtract( a, b );
var total = sum + difference;
return total;
};
compute( 2, 3 ); //returns 4
//EXAMPLE 3
// what is this method called?
var calculator = {
add: function ( a, b ) {
return a + b;
},
subtract: function ( a, b ) {
return a - b;
},
compute: function ( a, b ) {
var sum = this.add( a, b );
var difference = this.subtract( a, b );
var total = sum + difference;
return total;
}
}
calculator.compute( 2, 3 ); //returns 4
is this called function declaration?
function add( a, b ) {
return a + b;
}
Yes.
is this called function expressions?
var add = function ( a, b ) {
return a + b;
};
Yes. Notice that only the function(…){…} part is the function expression, the rest is a normal assignment (variable declaration with initialiser, to be pedantic).
what is this method called?
… {
add: function ( a, b ) {
return a + b;
},
…
}
Again, it's a function expression. Used as a property value in an object literal here, to define a method.
Are any one of these methods better than the other?
Function declarations are preferred over assigning function expressions to variables (there are slight differences). You should use expressions only where you need them as an expression (e.g. in IIFEs, conditional assignments, property assignments, property definitions, return statements etc).
Function declaration:
function add(a,b) { return a+b; }
A function declaration is defined at parse time for a certain script block. It can be called anywhere in the block without producing an error:
(function() {
add(3,3) //The function block has already been parsed, add() is available
function add(a,b) { return a+b; }
})();
Function expressions:
var add = function(a,b) { return a+b; }
Function expressions assign a variable to an anonymous function. These are evaluated at run time and cannot be called before being declared.
(function() {
add(3,3) //Error: add() has not yet been defined.
var add = function(a,b) { return a+b; }
})();
Object Methods:
Methods, are functions that are a property of an object.
var obj = {
propert1: 'property1 value',
add: function(a,b) {
return a+b;
}
};
These may be called via obj.add(3,3), however not prior to declaring the object via an object literal or assignment of a method to a property.
Is there a preffered way?
Declaring functions via a function declaration offers flexibility. It may however lead to unexpected results, For example(raised functions):
(function returnVal() {
function getSomething() {
return 'foo';
}
return getSomething();
function getSomething() {
return 'bar';
}
})(); //returns 'bar'
The return of the function may appear unexpected, however functions are raised during parse-time, and getSomething() is overridden.
Rewriting the code using a function expression produces the desired result
(function returnVal() {
var getSomething = function() {
return 'foo';
}
return getSomething();
getSomething = function() {
return 'bar';
}
})(); //returns 'foo'
Object methods on the other hand act much like function expressions however they are accessible under the object's name.
var obj = {};
obj.foo = function() { /*code*/ }
obj.bar = function() { /*code*/ }
They act similarly to function expressions, however this groups code under the ownership of obj. For clarity you may wish to choose this.

how to get a value which points to a function

i have a value like that
var myvalue = myfunction(1,2);
what I need is that
GETTING myfunction(a,b) as a string..
I mean not "myfunction's value"
hmmm, let me explain,
myfunction(1,2) returns 1+2=3
if I type
alert(myvalue)
it returns 3
but I need myfunction(a,b) AS IT'S TYPED when I use alert. NOT IT'S VALUE
think it like
var myvalue='myfunction(a,b)'
now, if i use Alert, it gives me myfunction(a,b)
how can I do that?
var myvalue = function()
{
myfunction(1,2);
};
myvalue is a anonymous function that calls myfunction with the specified parameters. You can call it, and if you print it for debugging, it will look something like:
function () {
myfunction(1, 2);
}
If you want to get the string value of a function, you can use the builtin toString method
var f1 = function(a, b) {
return a + b;
};
function f2(a, b) {
return a + b;
};
console.log(f1.toString());
console.log(f2.toString());
yields
function (a, b) {
return a + b;
}
function f2(a, b) {
return a + b;
}
But why do you want to do this?

Categories