Javascript chained scope and context [duplicate] - javascript

This question already has answers here:
Execute JavaScript code stored as a string
(22 answers)
Closed 8 months ago.
Is it possible to define a function run that acts like this?
a = run('var x = 100;')
b = run('console.log(x);') // prints 100
c = run('y = 1;')
d = run('console.log(y);') // prints 1
I tried several ways, using apply and passing the same context, binding a context to a function, returning a closure with a recursive call etc. but I can't seem to get anything to work.

Yeah, as MyLibrary says, you probably want eval, if you really want to do this. So:
var run = eval;
a = run('var x = 100;')
b = run('console.log(x);') // prints 100
c = run('y = 1;')
d = run('console.log(y);') // prints 1
would seem to work.
JavaScript allows assigning functions to variables, so you can set the run variable to eval. As far as eval, you may want to learn about it and as you can see from comments, its use in normal function creation is often discouraged.

Are you referring to eval function?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Related

passing variables into functions javascript [duplicate]

This question already has answers here:
Why I'm Getting NaN? [closed]
(3 answers)
Closed 2 years ago.
I can't quite seem to figure out why the variables I created don't return the way I would like. Simple math problems here, multiplication and division. Creating the variable outside of the function returns NaN, but calling within the function returns what I suspect.
Snippets below:
var p = parseInt(document.getElementById('watts').value, 10);
var e = parseInt(document.getElementById('volts').value, 10);
function calcAmps(){
var p = parseInt(document.getElementById('watts').value, 10);
var e = parseInt(document.getElementById('volts').value, 10);
document.getElementById('answer').innerHTML = p/e;
};
Now, using the variable within the function work fine. The math executes without issue. But if I comment out the variables within the function and attempt to use the global variables, I get NaN.
Any thoughts? Should be a softball question.
When initialized outside the function, the values are only fetched from the DOM once, when the script first runs. Inside the function, the values are fetched at the point that the computation actually happens.
To be clear and explicit, the following:
var p = parseInt(document.getElementById('watts').value, 10);
does not mean that a permanent dynamic relationship is established between the variable p and the input field. Instead, it instructs the runtime to fetch the current value of the field at the time the code runs. After that point, nothing you type in the input field will be reflected as the value of p.

jquery is not functional? [duplicate]

This question already has answers here:
JavaScript function binding (this keyword) is lost after assignment
(5 answers)
Closed 5 years ago.
firefox (v52.0), jquery
this works:
// example 1
$('html').find('body')
this works:
// example 2
var h
h=$('html')
h.find('body')
This doesn't work:
// example 3
var f
f=$('html').find
f('body')
I get
Error: Permission denied to access property "ownerDocument"
why?
but this works:
// example 4
var a
a = x => $('html').find(x)
a('body')
Example 3 doesn't work because find is called on the global context when you assign it to f. If you use call and pass in a valid jQuery object as the context, the code works. Try this
var f = $('html').find;
console.log(f.call($('html'), 'body').length)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Also, example 4 works because a can be translated to the following code, if written without an arrow function.
var a = function(x) {
return $('html').find(x);
};
It's just example 1, but with a wrapper function in order to take a parameter
No, jQuery is not functional
By looking at jQuery core source code:
https://github.com/jquery/jquery/blob/master/src/core.js#L51
You could see it hold state in this.
In f=$('html').find, the this of f is changed and no longer the this holding $('html') state
--
In this case, you are just proxy the method call. The this of find no change.
var a
a x => $('html').find(x)
a('body')

How do we explain javascript hoisting here? [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Why is no ReferenceError being thrown if a variable is used before it’s declared?
(3 answers)
Closed 5 years ago.
I wonder why the two code snipped below generate two different results as in reference below the two have to be the same as were are in global scope and placing var would not make a difference.
I was under the impression due to what explained below and the Javascript hoisting the two generate same output, but don't! why?
What is the purpose of the var keyword and when to use it (or omit it)?
console.log(a)
var a = 90;
// undefined
vs
console.log(a)
a = 90; // no var keyword
// Uncaught ReferenceError: a is not defined
When you put var keyword, what it does is it moves the var part as a declaration on that scope and makes it undefined. In the first case, with var:
console.log(a)
var a = 90;
// undefined
Gets rewritten as:
var a = undefined;
console.log(a)
a = 90;
// undefined
So, you get the undefined here, vs. your second case has it the same way, where there's no declaration or key in window object named a. Hope this is understandable.
The point here is, when you use a var keyword, immediately that's defined as undefined at the top of the scope before anything.

Why does `this` refers to `o` here (o.method)() instead of a global object [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
Suppose I have an object:
var o = {
prop: 3,
method: function() {return this.prop}
}
I was expecting this
(o.method)()
to return undefined, however it returned 3 meaning that this is set to o inside method. Why is it so? If you evaluate (o.method) separately, it evaluates to a standalone function, so I expected this to reference global object. Why, for example, the difference exists here:
(o.method)() vs (o.method || true)()
I know that o.method() will use o as context, the question is specifically about accessing the function first like this (o.method) and then calling it.
That's just how JavaScript's rules work. Unless you do some contortions, this usually means the thing before the . when you access the method prior to calling it. In this case, that's o.
The following statements are identical:
(o.method)();
o.method();
o.method.call(o);
o["method"]();
However, if you put the method on something else, it'll take on the meaning of the thing it's on:
var p = {prop: 42, method: o.method};
p.method(); // returns 42
var method = o.method;
var prop = 13;
method(); // returns 13
Note: As JavaScript grew to be much more than it was originally designed for, people realized that this probably wasn't the most intuitive way for this to work, so in ES6 if you use "Arrow Functions" (aka Lambda Functions) it won't rebind this.

Javascript variable declaration, why is this legal? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.

Categories