Javascript: attempting to access variable outside of function getting 'undefined' - javascript

I am trying to access the time_pressed variable outside of function held() by returning time_pressed and doing console.log(held()) outside of the function. It is console.log-ing undefined. Why is it not working and how can I do what I need to do to access said variable outside of the function?
Here is my code..
function held(){
var time_pressed;
document.onmousedown = function(e){
mousedown_time = getTime();
console.log(mousedown_time);
}
document.onmouseup = function(e){
time_pressed = getTime() - mousedown_time;
console.log('You held your mouse down for', time_pressed,'miliseconds.');
}
return time_pressed
}
console.log(held())

Consider the following function:
function held(){
var time_pressed;
return time_pressed;
}
console.log(held());
What do you expect the function to return? No value has been defined, so the value is undefined.
The only thing(s) you're doing in that function is assigning event handler functions to the document. Which means two things:
Those are separate functions and what they return isn't what this returns.
Those functions won't be executed until some later time when that even occurs.
You're successfully creating those event handlers. So it's not clear why you're trying to log some returned value. The function you're executing doesn't return anything, nor does it need to. There's nothing to be logged. Your event handlers will log to the console when they execute.

So, held() just sets up the handlers in your code. Your time_pressed variable holds nothing until the handlers fire to populate it. Give this a try:
function held(){
var time_pressed;
var mousedown_time;
document.onmousedown = function(e){
mousedown_time = getTime();
console.log(mousedown_time);
}
document.onmouseup = function(e){
time_pressed = getTime() - mousedown_time;
console.log('You held your mouse down for', time_pressed,'miliseconds.');
}
}
held();
edit: for the sake of completeness, getTime() needs to be defined. I went with:
function getTime(){ return new Date().getTime(); }

Related

How to use variables of event listeners outside the event listener function scope

I'm getting values based on the event.target, and I need to access those events outside the event listener function but I can't.
I don't know how to make use of return statement in this case.
And I can't have a global variable inside a function.
I also need to pass one of those variables to another js file, since I'm dealing with another html page.
Here's the code
[
//Click Event Listener Function to Redirect
let boxesContainer = document.querySelector('#content');
let clickHandler = function(event){
if (event.target.tagName === 'A'){
event.preventDefault();
let destination = event.target.getAttribute('href');
let operation = event.target.parentElement.parentElement.id;
console.log("a");
return [operation,destination];
}
}
// to avoid the code working in the other html page that doesn't have an ID = content
if (boxesContainer){
boxesContainer.addEventListener('click', clickHandler);
let operation = clickHandler()[0]; //Variable I want to use in another JS file
console.log(operation);
let destination = clickHandler()[1];// variable I will use for the redirect function
redirection(destination);
}
//Redirection Function
function redirection(destination){
window.location.href = destination;
console.log("Redirection done");
}

how to dynamically modify the return value from constructor function

I want to dynamically return different values based on the event that changes the value of var inside the constructor function. When constructor function is created I get the return of the default value which is equal to doA, when I invoke it the first time, I get a call to someFunction from doA. When the event happens, I can see that event variable updates it is reference to refer to doB function, however, when I invoke someFunction a second time, I still get a call to doA instead of doB. Any suggestion of can I achieve what I intent?
Thank you in advance
PS - the code bellow is not a working code, it just a representation of what I am trying to achieve
function doA(){
function someFunction(){};
function someFunctionB(){};
}
function doB(){
function someFunction(){};
function someFunctionB(){};
}
function Main(){
var event;
addEventListener('change', (event) => {
if(someCondition){
event = doA();
}
if(otherCondtion){
event = doB();
}
});
function someOtherFunction(){
}
return{
...event,
someOtherFunction
}
}
const main = new Main();
main.someFunction(); //calling someFunction from doA
//event changes here
main.someFunction() //intent to call someFuntion doB but still calling someFunction from doA
'''

print in console all the function which is being executed in javascript

I am creating AngularJS Javascript application in which i have 500/600 function in a single Directive,
Many functions are Inter connected with each other,
flow starts from the On load Event,
I want to know when i run the project,
which functions are being called on Onload Event
and i want to print the same on console,
I google it but i am not able to get anything,
is there any way to find out the functions which is being executed?
Call console.trace('calling on-load') to find stack-trace on on-load function. It would be better to call trace on the last function you expect to be executed to find all other function which has been called before.
You can wrap all your functions into "log wrapper":
var self = this;
function LogWrapper(action){
return function(){
console.log(action.name);
return action.apply(self, arguments);
}
}
//usage:
function ActualFunctionInner(arg1, arg2){
//some logic
}
var ActualFunction = LogWrapper(ActualFunctionInner);
var result = ActualFunction(1, 2);//console: ActualFunctionInner
Second solution is via Proxy:
let handler = {
get(target, propKey) {
var inner = target[propKey];
return function () {
console.log(inner.name);
return inner.apply(this, arguments);
};
}
};
var loggedSelf = new Proxy(self, handler);
var result = loggedSelf.ActualFunction(1, 2);//console: ActualFunction

Reassign variables stored in closure using a callback or global function

EDIT
Let me get more to the point. I'm trying to create a psuedo promise implementation. The idea here being that I have a callback that won't be executed until an asynchronous call is received. So I'm simply queueing up all the calls to this function until the time at which it's notified that it can be executed. The queue is emptied and any further call to the function is SUPPOSED to execute immediately, but for some reason, the function is still queueing. This is because, for whatever reason, my redefinition of the runner function is not working correctly. The code below was my sleep deprived, frustrated version of every thought that went through my head. Here's the actual code:
function Promise(callback){
var queue = []
, callback = callback
, runner = function(){
queue.push({
context: this,
args: Array.prototype.slice.call(arguments, 0)
});
}
;//var
runner.exec = function(){
for(var i = 0, ilen = queue.length; i < ilen; i++){
var q = queue[i];
callback.apply(q.context, q.args);
}
runner = callback;
};
return runner;
}
test = Promise(function(){
$('<div/>').appendTo('#output').html(Array.prototype.slice.call(arguments,0).toString());
});
test(1,2);
test(3,4);
test.exec();
test(5,6);​
http://jsfiddle.net/a7gaR/
I'm banging my head against the wall with this one. I'm trying to reassign variables in a function from a call outside the function itself (ideally by passing a reassignment function as a callback). In the example I posted on jsfiddle, I made a global function that, in theory, has a reference to the variables contained within its parent function. Upon calling that external function, I expect it to reassign the values that the other function is using. It doesn't seem to work this way.
window.test = function temp() {
var val = 7,
func = function() {
return val;
};
window.change = function() {
window.test.val = 555555;
$('<div>Changing ' + val + ' to ' + window.test.val +
'</div>').appendTo($output);
val = window.test.val;
temp.val = window.test.val;
func = function() {
return 'Why isn\'t this working?';
}
}
return func();
}
var $output = $('#output');
$('<div/>').appendTo($output).html('::' + test() + '::');
window.change();
$('<div/>').appendTo($output).html('::' + test() + '::');
http://jsfiddle.net/YhyMK/
The second time you call test you're creating a new local variable called func and defining a new window.change that closes over that new variable. The changes you made to the original func by calling the original window.change are not relevant in the second call.
Also note that the following line:
window.test.val = 555555;
...does not modify/refer to the val variable in the outer function. window.test.val refers to a property named val on the test object (which happens to be a function), not any local variable.
You are trying to refer to a local variable in a function with the syntax func.varname. That won't work, that's not the way local variables work.
I finally created a function that would perform this operation. The gist for it is here: https://gist.github.com/2586972.
It works like this...
You make a call to Defer passing the callback whose functionality you'd like to delay:
var deferredCB = Defer(function(){ console.log(this,arguments) };
deferredCB will now store all of the arguments you pass allowing them to be executed at some later date:
defferedCB(1);
defferedCB(2);
Now, when you're ready to perform the operation, you simply "execute" deferredCB:
defferedCB.exec();
Which results in:
// window, 1
// window, 2
All future calls to deferredCB will be executed immediately. And now that I'm thinking about it, I'll probably do a rewrite to allow you to reset deferredCB to it's pre-executed state (storing all the arguments again).
The key to making it work was having a wrapper function. Javascript simply won't let you reassign a function while it's being executed.
TADA!!!

how to get a reference for the caller element when the function has already a parameter

function myFunction(par) {
...
}
el1.onclick=myFunction(5);
el2.onclick=myFunction(7);
How to get a reference for the caller element inside myFunction?
In your example, you are assigning the return value from myFunction(5) to el1.onclick, and the return value from myFunction(7) to el2.onclick.
Take the following example:
el1.onclick=myFunction(5);
In the above example, myFunction(5) is executed. Then the return value of that function, let's call it myval, is assigned to el1.onclick. This is equivalent to:
var myval = myFunction(5);
el1.onclick = myval;
It's not clear that this is what you intended. For this to work, the return value from myFunction would need to be a function (or a string of Javascript) to be executed later.
It is inside that function that you would refer to the caller element. this inside that function will return the element on which the event is currently being called.
//this is saying call this function and asign what it returns to onclick
el1.onclick= myFunction(5);
You want to use a closure
el1.onclick = function(){myFunction(5);}
To reference the element you can pass the object in
function test(elem, x){
elem.innerHTML = x;
}
document.getElementById("foo").onclick = function(){ test(this, 1); }
example 1
or you can use call so that within the listener, this references the element.
function test(x){
this.innerHTML = x;
}
document.getElementById("foo").onclick = function(){ test.call(this, 1); }
example 2

Categories