This binding in node.js [duplicate] - javascript

This question already has answers here:
In what object does Node.js store variables?
(3 answers)
Closed 8 years ago.
I am puzzled by some node.js behaviour, which is different fron Google Console.
Here is a simple code
var t = "GLOBAL";
var objet = {
t : "LOCAL1",
test : function() {
console.log(this.t,t);
}
};
var objet2 = {
t : "LOCAL2",
test : objet.test
};
var test = objet.test;
objet.test();
objet2.test();
test();
This code yiels different result.
In node.js, i have these results :
LOCAL1 GLOBAL
LOCAL2 GLOBAL
undefined 'GLOBAL'
In chrome console :
LOCAL1 GLOBAL
LOCAL2 GLOBAL
GLOBAL GLOBAL
I thought that calling directly the function binded to test.t, this would be binded to the global scope, it is the case in chrome, but node in node.js.
Note that if i remove the varin the first line, the node.js version give the same result.
So what is going one ? It seems that there is a scope in node.js that i am missing ?
Does somebody have a clue ?

In NodeJS, the default scope is that of the module. Global scope is even bigger than the module, which is what this refers to. In Chrome, the global scope is window, which is what this is.
See the module documentation and more importantly, globals.

Related

How are 'let' variables accessed in devtool's console? [duplicate]

This question already has answers here:
Do let statements create properties on the global object?
(5 answers)
Closed 2 years ago.
If you open chrome devtool and enter the following:
// The iife is irrelevant
let r = (() => { return 2; })();
and then evaluate r you'll see:
r
2
but window.r and globalThis.r both return undefined. I know let is block scoped but where is the r parent object? What block am I in, in the devtool that I can access r directly but it's not on any global object?
Apologies, I'm on my phone, so can't really verify. But I'm pretty sure there is a 'scope' tab as part of the Dev tools. If you're debugging I'm pretty sure you can see variables there in the current scope. But it's not available in the normal console
https://developers.google.com/web/tools/chrome-devtools/javascript#scope
Edit, just re-read your question, and this doesn't really answer your question description, but does kind of answer your question title. So probably going to leave the answer here for future ref
The code is evaluated in global scope.Variable "let" declared Globally (outside any function) have Global Scope.

Why does a variable assignment not throw a ReferenceError when the variable is not defined - JavaScript [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 3 years ago.
I've tried this in Chrome, Opera, Microsoft Edge, Internet Explorer and Mozilla Firefox and still gotten the same case: A ReferenceError exception is not thrown that the variable I assigned a value is not defined.
The syntax is:
// Where `identifier_name` was not formally declared/ initialized.
(function() {})(identifier_name = 2)
Why does this behavior occur?
Edit: Just to add, this doesn't work if what is being assigned is a property of an object i.e.:
// Throws a ReferenceError that `object_name` is not defined.
(function() {})(object_name.property_name = 2)
Thats what we used to call the horror of implicit globals
You basically create a global variable by accident. You can "use strict";mode to prevent that.
Your second snippet does not work because you are trying to access a variable that was not declared yet, which is different from assigning to a variable that was not declared already (cause that implicitly declares the variable).
You have declared a global variable here in both cases without the 'var' keyword.

Does an if statement create a local scope? [duplicate]

This question already has answers here:
javascript variable scope in the IF statement
(5 answers)
Closed 6 years ago.
I am currently reading through some javascript tutorials and I came upon this bit of example code from here: http://www.w3schools.com/js/js_if_else.asp
if (hour < 18) {
greeting = "Good day";
}
In this example, the greeting variable is not prefixed with a var statement. Now I looked up what this means, and my understanding is that it causes java script to look to a higher scope, if no variable is discovered by the global scope it creates it.
So is this tutorial doing this because the if statement's block is a local environment? If so does that mean that if I were to have some code that looked like this:
if (condition){var x=10};
else {var x=5};
then there would still be no global variable x for me to call?
In JavaScript (ES5), an if statement does not create a local scope when declaring with var. Local scope is created with a function.
W3Schools is notorious for using bad practices in their code samples, and you've found one example of this. They are creating a globally-scoped variable.
Blocks will only create a local scope for variables declared with the new let keyword. If you're using an older version of JavaScript, or if you're using the var keyword, then the variable is scoped to the innermost function that the variable is declared in.
Variables declared via var outside of any function are scoped to the window (global) scope.
{
var x = "hello world";
}
document.getElementById("var-value").innerHTML = x;
<span id="var-value"></span>
In the above snippet, if you replaced var with let, it would produce an error because x is undefined.
{
let x = "hello world";
}
document.getElementById("var-value").innerHTML = x;
<span id="var-value"></span>
You would be able to get the value of x outside of the if..else. This is due to JavaScript having function scope rather than block. I created a JSFiddle of your example, which can be found at https://jsfiddle.net/h4gjb8mt/
Example:
var condition = true;
if (condition) {
var x=10;
}
else {
var x=5;
}
console.log(x);

Not defining the type of variable (Automatic global variables) [duplicate]

This question already has answers here:
Define a global variable in a JavaScript function
(17 answers)
Closed 7 years ago.
I recently came across this http://www.w3schools.com/js/js_scope.asp where I learned about "Automatic Global variables". Here is how you use it:
// code here can use carName
function myFunction() {
carName = "Volvo";
// code here can use carName
}
However, how high can it go? I am worried other files can access it to if its that global. If I am using AngularJS, can other controllers use it? Can other files use it?
In JavaScript, creating a variable without var is the same as setting it on the global object as a property (and in the browser, global is window:
nameWithoutVar = 1;
// the above is the same as
window.nameWithoutVar = 1;
This means that any other script loaded in the browser for the page can access nameWithoutVar, the same as they can access location, document, etc.
Global variables are considered an extremely bad idea for this reason, because everything is using the same namespace. If you must use a global variable†, be sure to document it, and try to namespace it so that it is unlikely to conflict with any other variable.
†If you're not sure, you probably don't have to.

How do I access a local variable dynamically (via a String form of its name) from a closure scope? [duplicate]

This question already has answers here:
How can I access local scope dynamically in javascript?
(4 answers)
Closed 8 years ago.
In Javascript, I'm used to being able to access variables within a known namespace "dynamically" (correct me if I'm using the wrong word here) by using the [] operator. For instance (from the global namespace):
var a = 1;
window['a']; # => 1
Or from a object-type namespace:
var a = { b: 1 };
a['b']; # => 1
And I'm familiar with the basics of how this is determined:
var a = function(){ return this['c']; };
var b = { c: 1 };
a.apply(b); # => 1;
But within a function itself, how do I access local variables I've just instantiated (or redefined) using var?
Namely, I want the following function call to return 1 but without calling a:
function(){
var a = 1;
return a;
}
You can't use window['a'] because a is defined locally, and you can't use this['a'] because this changes depending on the context from which the function is called.
In a realistic setting, I'd simply refactor to avoid dynamically creating and accessing local variables because it's generally a bad idea anyway, but as an academic question, I'm curious as to whether it's possible to access a via its string name at all.
You're mixing up local variables (which are not properties of an object) with properties (which are not local variables). There is no answer to your question, or, rather, the answer is "it can't be done".

Categories

Resources