why do parenthesis preserve this when called in same statement [duplicate] - javascript

This question already has answers here:
JavaScript object functions and `this` when unbound and returned in expression/parens
(2 answers)
Closed 5 years ago.
Consider the following variables:
var obj = {
value : 'from object',
getValue : function() { return this.value; }
};
var value = 'from global';
Now, obj.getValue() evaluates to 'from object'. And if I get a reference to just the getValue function and call it:
var f = obj.getValue;
f();
f evaluates to 'from global'.
My question is why does (obj.getValue)(); return 'from object'?
I would have thought that the first set of parenthesis would evaluate to a plain reference to the getValue function and then when calling that result, this would be the global context. Why does the interpreter assume this is a call on the object?

When you call var f = obj.getValue();, you are running the getValue method from the object. When you call var f = obj.getValue;, you are reassigning the function to f, and then when you call f, it has no ties to obj, it is simply called as a global function.

Related

Why are anonymous functions passed into variables? [duplicate]

This question already has answers here:
function.name returns empty string if the function is added to an object by property
(2 answers)
Closed 1 year ago.
So, I'm using freecodecamp and it says that the following function is anonymous:
const myFunc = () => {
const myVar = "value";
return myVar;
}
console.log(myFunc.name);
Well, how come it's anonymous if its name is clearly "myFunc"?
You are setting myFunc to reference an anonymous function. myFunc has a name, the anonymous function it references does not.
const myFunc = () => {
const myVar = "value";
return myVar;
}
// This returns myFunc name
console.log(myFunc.name);
// This returns anonymous function's name which is blank
console.log(
(() => {
const myVar = "value";
return myVar;
}).name
);

Ridiculous scoping in Js [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 1 year ago.
Can someone explain to me why the second function call returns undefined? I see no reason for that. The reference of the object method is stored in a variable, so it should be printed out. Why the result is undefined? The first function call is successful and the only difference is that the second one is stored in a variable.
const module = {
x: 42,
getX: function() {
return this.x;
}
};
//1 - returns 42
console.log(module.getX());
//2 - returns undefined
const unboundGetX = module.getX;
console.log(unboundGetX());
Because unboundGetX function is called by the global window variable, unboundGetX() it's like writing window.unboundGetX() so the this will refer to the global scope which is "window" object so it's also like you wrote return window.x which is logically "undefined".
it will be better to bind your scope to the same object like this :
const module = {
x: 42,
getX: function() {
return this.x;
}
};
console.log(module.getX());
const unboundGetX = module.getX.bind(module); // we bind getX function to module scope instead of the global scope (which is the window variable)
console.log(unboundGetX());

How can i use varaible from outer scope of the callback function [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 3 years ago.
How do I use the variable from the outer scope of the function. I have created this simple example here
var view = {
init(){
const targetOne = document.querySelector(".targetOne");
const targetTwo = document.querySelector(".targetTwo");
var val = "outer scope";
targetOne.addEventListener('click', (e) => {
console.log('target one', val)
});
targetTwo.addEventListener('click', this.handleEvent);
},
handleEvent(e) {
console.log('targetTwo ', val);
}
}
view.init();
JS fiddle link: https://jsfiddle.net/jr7b521x/50/
For the targetOne callback I can use the variable val, but when i define a function for the targetTwo callback, that variable val is not defined in the scope. I feel like I am missing something very simple here, I refreshed on scope chaining and closure but I am not able to get it
the variable val is within the scope of the init () function
for you to get it in the handleEvent function you will need to pass it by parameter or it must be a property of the view object

What do closures mean exactly? [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 8 years ago.
I've read about closures many times here.
But I'm really confusing to know exactly what do closure mean?
Is variable a closure ?
Or, is function is a closure ?
Or, both can be called a closure ?
A closure is a container for variables, it lets a function access variables from the scope where it was created even when it is called in a different scope.
Example:
function a() {
// a local variable
var x = 42;
function f() {
// use the local variable
return x;
}
// return the function f
return f;
}
// call a to get the inner function
var fx = a();
// call the inner function from out here
var y = fx();
// now y contains the 42 that was grabbed from the variable x inside the function
When the function f is created, it has a closure with it that contains the variable x from the scope where it was created. When the function is called from the global scope it can still access the variable x from the local scope as it is in the closure.
You could simulate the function of the closure by putting variables in an object, and send that along with the function, so that the function can use it later:
function a() {
// a "closure"
var o = { x: 42 };
function f(closure) {
// use the "closure"
return closure.x;
}
// return the "closure" and the function f
return { f: f, o: o };
}
// call a to get the inner function and the "closure"
var fx = a();
// call the inner function with the "closure"
var y = fx.f(fx.o);
// now y contains the 42 that was grabbed from the variable x in the "closure"
Note: The closure contains any identifer in the scope, so in the first example the closure for the function f also contains the identifier f which is the function. The function can call itself using the name f from anywhere, although the identifier f is local to the function a.

What is going on with JavaScript scope here? [duplicate]

This question already has answers here:
Why does shadowed variable evaluate to undefined when defined in outside scope?
(6 answers)
Closed 9 years ago.
I've written the following snippet of code:
var f = function() { document.write("a"); };
function foo() {
f();
var f = function() { document.write("b"); };
}
foo();
I expected the function that prints a to be called, but it instead gives a runtime error about calling an undefined value. Why does this happen?
It's about variables hoisting http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html , http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/
You code is eqvivalent to the next one;
var f = function() { document.write("a"); };
function foo() {
//all var statements are analyzed when we enter the function
var f;
//at this step of execution f is undefined;
f();
f = function() { document.write("b"); };
}
foo();
Since (just like in java) you don't have to worry about the order you define things in in a file a certain situation occurs. When you redefine the variable f it blanks out the other version of f but it is not defined until after so when f is called you get an error.

Categories