Attempting to pass a string to a constructed function - javascript

still floundering around in my attempts to understand functions. How would I go about constructing a function with values I want to pass to it?
var box = $('#box1');
function pushCard(arg1) {
if (this.style.opacity == 0.5) {
this.style.opacity = 1;
}
else {
this.style.opacity = 0.5;
window.alert(arg1);
}
}
box.click(pushCard('String'));

tl;dr: be aware of the difference between functions / function results and when functions are passed as values / when they're called (and their result is passed)
The culprit is with this line:
box.click(pushCard('String'));
You're calling box.click() with "something". JavaScript needs to evaluate expressions before passing them as function arguments.
In this case, you instruct JavaScrip to run box.click(pushCard('String')) = call box.click with value of pushCard('String') as first parameter.
In order to do this, JavaScript first needs to evaluate pushCard('String') by running pushCard with value 'String' as first parameter (this doesn't need more evaluation since it's already a value).
The result of pushCard('String') is undefined (you're returning nothing from that function). So in effect, it's the equivalent of box.click(undefined).
This is what you want:
box.click(function() {pushCard('String')});
(or with ES6 arrow functions: box.click(() => pushCard('String'));)
In this case, you're assigning box.click() a function. This is what jQuery .click()` expects, a click handler which will run (be evaluated) then the click happens, not when the click handler is assigned.
In JavaScript, you can pass functions as values, and they are evaluated when explicitly called:
function test() {
alert('I have been called');
}
function delay_it(handler) {
setTimeout(function() {
handler(); // ⇽ call given function
}, 1000);
// shorter: setTimeout(handler, 1000);
}
// Wrong (we're calling test() by ourselves and passing the result (undefined) to delay_it
delay_it(test());
// Correct (we're giving test as function to delay_it, delay_it will call the function)
delay_it(test);

Related

js debounce logic understanding

Wanted to see if experts here help explain how to understand the below debounce logic better. I got this from an Udemy course but the video only got so much explanation. From the code below.. this is what I understand it does - everytime an "input" is detected setTimeout inside debounce function will execute and after 1 second it'll remove the timeout.
How does the spread operator and the "args" come into play in this?
I understand the spread operator takes in an array and then "spreads" it out as separate arguments into the function parameter. Am I misunderstanding how the func.apply works here? How does the return(...args) read the input value arguments?
It seems like "onInput" is func and the return values from "onInput" is passed as arguments to ...args?
const debounce = func => {
let timeoutID;
return (...args) => {
if(timeoutID) clearTimeout(timeoutID);
timeoutID = setTimeout(
() => func.apply(null, args),
1000
);
};
}
const onInput = event => {
fetchData(event.target.value);
};
input.addEventListener("input", debounce(onInput));
A few things to clarify:
debounce returns a (anonymous arrow) function. It doesn't do much more than that, except that it provides a closure for the variables func (the argument passed to debounce) and timeoutID. So when you call debounce(onInput) the returned function will know about onInput.
The above-mentioned returned function becomes the handler for the input event. So when that event triggers that anonymous arrow function is called with the event object as argument. So args will be [event object]. This anonymous function will clear any pending timer event and will schedule a new one that will call func.apply(null, args).
When the timer expires without being cleared, then func.apply(null, args) will be called. We know what func is: onInput and we know what args is: [event object]. So that means we effectively call onInput with the event object as argument.
As to your questions:
How does the spread operator come into play in this?
It is the rest syntax, and allows to capture all the arguments into one array.
How does the "args" come into play in this?
As explained above, as the event handler is called with one argument, args will be initialised to an array with the same arguments that the event handler would get, i.e. with the event object.
Am I misunderstanding how the func.apply works here?
All you wrote about it is that the function will execute. apply is a method that calls the function with a specific value for this (which is not the goal here, so just null is provided), and with an array that should be used as arguments in the call. As args is exactly that array of arguments we got, and we just want to pass them on, that is what is passed here as well.
It should be said that in modern JavaScript you'd achieve the same result with func(...args);
How does the return(...args) read the input value arguments?
First of all that is not the complete statement. The complete statement includes the whole arrow function, which is the object that is returned here. Like explained above, debounce returns a function (object).
This code "only" returns that function, it does not read input value arguments. It provides the function that will later do this. Realise that debounce is called now, while that returned function is only called when the event fires.
Rewritten...
It may clarify things when rewriting the code in a slightly different way. I hope it better highlights the difference between returning a function and executing it. This can happen at different times.
function debounce(func) {
let timeoutID;
// Define a local function. Don't execute yet.
// It takes any arguments, as it will just remember them
// for passing them to the original function later on (after timer).
function debouncedFunc(...args) {
// If we had a pending timer job, clear it, as we want a new one.
if (timeoutID !== undefined) {
clearTimeout(timeoutID);
}
// Create a function to execute later. It should itself
// execute func with the arguments we already know about.
function executeFunc() {
// This is the more modern syntax to do func.apply(null, args):
// It is easier to read; we just call func with some known arguments
func(...args);
}
// Schedule that function to run later, and get a handle for that job
timeoutID = setTimeout(executeFunc, 1000);
}
// Return the new function object to the caller.
// They can call it with some arguments, or let
// some other API call it for them (like with addEventListener)
return debouncedFunc;
}
function onInput(event) {
fetchData(event.target.value);
}
// Get a function object
const debouncedInputHandler = debounce(onInput);
// Make that function the event handler
input.addEventListener("input", debouncedInputHandler);

Why function returns unexecuted

If I write this code:
var foo = function (){
var x = 5;
return (function (){ return x;})();
}
alert(foo());
it alerts 5, as intended. But, if I do not use IIFE:
var foo = function (){
var x = 5;
return function (){ return x;};
}
alert(foo());
it alerts
function(){return x;}
I understand that in the first example IIFE runs and whatever it computes gets returned.BUT, if not using IIFE function returns without being executed.
Why is function returned before it is executed?
Functions in JS are first class objects. You can treat them in the same way as you can treat any object, including pass them about between functions.
If you don't do something to call a function, then it doesn't get called.
So is function(){return x:} which gets alerted in the second option a string
It is a function.
Functions, like any object, have a toString method.
alert() expects to be passed a string. Since you pass it an object, it will get converted to a string, which is done by calling toString().
Basically you are not executing the function before returning anything in the second example. You are just returning a function definiton with this row: return function (){ return x;};. This is why the function returns just the function that you placed after the return.
Functions are never called automatically. They can be passed as arguments, returned as values, assigned to variables, etc. and this just moves around references to the function. In order to call a function, you have to use the () operator.
Your first example does this by calling the function in the IIFE. "II" stands for "Immediately Invoked", and refers to putting () right after the anonymous function expression, so that you define it and then immediately invoke it.
In your second example, you simply return the function, and then pass it as an argument to alert(). alert() has no reason to call the function (it's not like map() or forEach(), which take a callback argument and are specified to call the function). If you want to execute the function, you need to call it explicitly, e.g.
var foo = function() {
var x = 5;
return function() {
return x;
};
}
alert(foo()());
The double () means to first call foo, then call whatever it returns, and finally pass the result to alert.

Why can't the generators next function be a callback function for an event listener [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I was experimenting with generators for a bit. When I tried this piece of code I got unexpected errors:
Uncaught TypeError: Method [Generator].prototype.next called on incompatible receiver #
or
TypeError: CallStarGeneratorMethodIfWrapped method called on incompatible HTMLButtonElement
My question, does it not work ? What is the meaning behind those error messages ? And most importantly; Why is first().next not handled as a normal function ? Why does the addEventListener care about the origins of the first().next function. Type first().next in the console. It says function. Below is out commented a similar function to the next except it produces always the same result.
The code, that you can try to reproduce:
<html>
<button id="test">Click</button>
<script>
var first = function* (){
console.log("first click");
yield true;
console.log("second click");
yield true;
};
document.getElementById("test").addEventListener('click', first().next);
/*var wouldwork = function (){
console.log("would work");
return { value: true, done: false };
// same as the next returns
};*/
/*document.getElementById("test").addEventListener('click', wouldwork);*/
</script>
</html>
Another option would be to put next with the correct context in another function. To do that we store the iterator in a variable.
var iterator = first();
document.getElementById("test").addEventListener('click',
function (event){return iterator.next();}
//context of next is always the correct one
);
If that happens more often it can be a good idea to create a new function named createNext that returns a next function in a more pure functional style
var createNext = function (generatorFunction){
var iterator = generatorFunction();
return function() {
return iterator.next();
};
};
document.getElementById("test").addEventListener('click',
createNext(first)
);
jsFiddle Demo
The way that event listen works is that it will call the function handle using call and assign the this binding from its execution context to the called function handle. So this is going to be bound as the context for next being called. That is why it doesn't work as written.
Next, there is the issue of actually getting the function from your generator function for iteration. "Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead.". This means that yes, first().next is a function object, but it isn't the handle you want to pass. You simply want to use the iterator function itself, but that would be first(), so how does that work if you want it to call next each time?
An option here is simply to take your generator function and pass the iterator function in later as a binding. In order to maintain the iterator function's binding inside of .next, you could do this:
document.getElementById("test").addEventListener('click', first().next.bind(first()));
This will bind the iterator function for first() to the iterator function's .next function. Kind of messy. The first call to first() exposes the iterator function and then accesses its next function, the second call simply binds the next function's this to the iterator function which is otherwise overwritten when the eventListener overrides the this binding using call.
You can read more in general about these generator functions and their iterators here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

setTimeout with or without anonymous function? What's the difference?

I used this code (followed by an xmlhttprequest that fills the "tcap" textarea):
st=setTimeout(checkme(),4000)
where checkme() is:
function checkme() {
if (typeof (st) != 'undefined') clearTimeout(st)
if (document.getElementById("tcap").innerHTML.length > 0) {
document.getElementById('waitmsg').style.display = 'none'
} else {
st = setTimeout(checkme(), 1000)
}
}
If I run it, it freezes Firefox 19 with no error message.
But if I replace the first argument (both in code and in the checkme() function) with:
st=setTimeout(function(){checkme()},4000)
it works correctly.
So my question is: what's the difference in calling the checkme() function with or without the anon function? Why in the first case it freezes Firefox?
Thanks
You need to remove the parens in
st=setTimeout(checkme(),4000)
so instead:
st=setTimeout(checkme,4000)
otherwise, the function is invoked right away.
Since you have the same error inside the checkme function, it probably kills your browser due to unbounded recursion.
setTimeout accepts a function as an argument, and the correct way to pass a function as an argument is either defining it as an anonymous function, or just providing the function name. If you use parenthesis(brackets), you aren't actually passing a function: You are executing the function and passing the result of the function to setTimeout.
Hence, when specifying a function in setTimeout, and anywhere else you need to pass a function as an argument, you should not use parenthesis.
You shouldn't be using the parenthesis within the setTimeout function. You should only be passing in a reference to the method. What you are doing is invoking the method and passing the return value in to the set timeout method.
If you are using setTimeout(checkme(),4000), you are passing the return value of checkme();
But if you want to pass it as a function you need to do in following ways
setTimeout(function(){checkme()},4000)
or
st=setTimeout(checkme,4000)

Difference between 2 jquery binds

function runSomething () {
// some stuff happens
}
$(selector).bind('event', runSomething());
$(selector).bind('event', runSomething);
What's the difference between these 2 versions of the bind?
Here's a practical example:
http://jsbin.com/icajo/edit
Can somebody explain why works the way it does.
I'm trying to get multiple buttons to run the function upon the event, what should I do?
In first case you bind result of runSomething() call, in second - function itself.
update
#JSNewbie, run this and tell what you see in each alert.
function runSomething () {
return 3;
}
var a1 = runSomething();
var a2 = runSomething;
alert(a1);
alert(a2);
In javascript, passing a set of parameters to a function invokes the function, it gets evaluated to the functions return value.
var test = function() { return 1; } // Creates a new function that returns 1
alert(test.toString()); // => "function () { return 1; }"
alert(test().toString()); // => "1"
Even alert itself is just a variable that points to a function.
alert(alert); // => "function alert() { [native code] }"
So, if the first example, when calling runSomething(), it immediately evaluates that function, then passes the return value as a parameter to bind(). In your case, it evals the alert() as the page is loaded, then passes undefined to bind()
In your second example, using the variable runSomething the function itself is passed to bind(). Bind then uses that function only when the event has been raised.
To really blow your mind, you could have function that returns a function, then evaluating the function (like in your first example) is correct... For example
var counter = 0;
function GenerateNext() {
counter++;
return new Function("alert(" + counter + ")");
}
a = GenerateNext();
b = GenerateNext();
b() // will alert 2
a() // will alert 1
$(selector).bind('event', GenerateNext()); // alert 3
$(selector).bind('event', a); // alert 1
$(selector).bind('event', b); // alert 2
It just all depends on what you are trying to do; pass the function itself, or pass the return value of the function.
In the first line the function runSomething is executed within the bind statement, and that what it returns is bound to the event, for example if your runSomething function returns another function then that function is bound, and will be executed upon the event.
On the second line the runSomething function is not executed at that line, and is only only execute when "event" happens.
In javascript functions are treated as variables. Adding the "()" will call the function, and pass the result of the function (which could be 'undefined' if the function returns nothing). The second is the proper way of using the bind method, because it gives a handle to the function to call when the event is triggered.
$(selector).bind('event', 'runSomething()'); (notice the extra quotes around 'runSomething()')
run the function runSomething() when the event is received.
$(selector).bind('event', runSomething);
sets the function runSomething() as the callback function for the event, which means it will receive whatever parameters are included in the event, often this is useful for currentTarget (so you can use the same event on many buttons) or to get specific information from the event (mousemove returns the X,Y location of the mouse as it is triggered).
So if you needed to access the event object that is returned when the event is triggered, the first version wouldn't work properly.
function runSomething(event){
console.log(event); // this would show the event object if the second code is used.
}

Categories

Resources