This question already has an answer here:
Why can’t I assign values to a variable inside a named function expression with the same name?
(1 answer)
Closed 3 years ago.
var functionVariable = function functionExpressionName() {
functionExpressionName = 1;
console.log(functionExpressionName) // function
};
functionVariable();
If You run this example you can see we can not reassign to functionExpressionName anything.
But this is also interesting we can reddeclare functionExpressionName and after this we can assign anything to functionExpressionName
var functionVariable = function functionExpressionName() {
function functionExpressionName() {
}
functionExpressionName = 1;
console.log(functionExpressionName); // 1
};
functionVariable();
If you enable strict mode, the error becomes a bit clearer:
'use strict';
var functionVariable = function functionExpressionName() {
functionExpressionName = 1;
console.log(functionExpressionName) // function
};
functionVariable();
Uncaught TypeError: Assignment to constant variable
The function name is un-reassignable inside the function, but you can create a new variable with the same name inside the function body. One way of looking at it is that the function name is declared with const just outside the function body:
var functionVariable = (() => {
const functionExpressionName = function () {
functionExpressionName = 1; // Clearly wrong - functionExpressionName is a const
// but it would work if you declared a *new* variable,
// which has a different lexical binding
console.log(functionExpressionName) // function
};
return functionExpressionName;
})();
functionVariable();
This isn't exactly what happens, but it's pretty close.
Related
This question already has answers here:
How do I pass variables between functions in Javascript?
(3 answers)
Closed 6 months ago.
I am learning Javascript. I want to pass variable from one function to another. I am trying to catch option in funTwo but I do not want to declare the variable as global or use var.
function funOne(one) {
let tags = '<div class= "options">' + arr[1] + '</div>';
const option = options_list.querySelectorAll(".options")
}
function funTwo(two) {
option.classList.add("correct")
}
In javascript, variables declared with const or let are scoped: this means they exist and are accessible only in the current scope.
When you declare a variable inside a function, it is inside the function scope and inaccessible from anything that is not in that scope, including other functions. If you want to use this variable, you need to pass it either as parameter or returning it from a function call.
function b(value) {
console.log(value);
}
function a() {
const foo = 1;
b(foo);
}
or
function b() {
let value = a();
console.log(value);
}
function a() {
return 1;
}
Yes, you can return option from funOne and get it in funTwo.
function funOne(one){
let tags = '<div class = "options">' + arr[1] + '</div>'
const option = options_list.querySelectorAll(".options")
return option
}
function funTwo(two){
const option = funOne() // the function will return option.
option.classList.add("correct")
}
This question already has answers here:
What does 'var that = this;' mean in JavaScript?
(6 answers)
Closed 3 years ago.
I've seen things like this:
function fnx(){
ctrl = this;
this.thisedVar = "thisedVar from fnx"
}
I'm trying to figure out what is it useful for. if that function is executed and then this is compared to ctrl, they are the same:
fnx();
console.log(this === ctrl) // true
That's why I don't understand what is the purpose of assigning this to a variable.
Can anyone explain it, please? Thanks.
var a = function() {
var THIS = this;
this.s = "Hello World";
this.runMe = function() {
window.setTimeout(function() {
console.log(this.s);
}, 100);
}
}
var a2 = function() {
var THIS = this;
this.s = "Hello World";
this.runMe = function() {
window.setTimeout(function() {
console.log(THIS.s);
}, 100);
}
}
b = new(a);
b.runMe();
b2 = new(a2);
b2.runMe()
Outputs:
undefined
Hello World
Class a (object b) returns undefined because that this is in the scope of the callback.
Class a2 (object b2) returns Hello World because that this belongs to the class a2.
When you assign a variable to a value without using var it refers to global variable. So if you are assigning this to ctrl it means the your are assigning Window obecjt this to a global variable `ctrl.
So when you compare ctrl with this (again Window) object, it is same since you are matching after function execution.
In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called.
You assign THIS to a variable so you save this value.
Read more: https://medium.com/tech-tajawal/javascript-this-4-rules-7354abdb274c
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
What underlies this JavaScript idiom: var self = this?
(10 answers)
Closed 5 months ago.
In this code snippet, why is it that this.identifier doesn't work but _self.url works?
getConfig() {
let _self = this;
return function () {
this.page.url = this.url || window.location.href;
this.page.identifier = _self.identifier;
this.page.category_id = this.categoryId;
this.language = this.lang;
};
}
So does let _self = this actually do?
Functions have something called a context. A context is the object the function is being called on.
let person = {
name:"bill",
speak:function(){
console.log("hi i am "+this.name)
}
}
if you were to do person.speak()
it will be called on the object that was defined. The variable person is the context
so when you say this. it's the same as saying person.name
Now you can attach the function to something else.
var newperson = {name:'jill'}
newperson.speak = person.speak;
this will print hi i am jill when it's called.
Now on to step two.
GetConfig returns a function, however this function is not attached any object.
Check this out.
let person = {
name:"bill",
getSpeakFunction:function(){
return function(){
console.log('hi my name is '+this.name)
}
}
}
let func = person.getSpeakFunction()
Now the function func is all by himself.
Now when it is called who is this who the hell are you talking about.
That is what the function is thinking.
So we can help the function out by saying.
let person = {
name:"bill",
getSpeakFunction:function(){
let context = this; //listen hear function this is what i am talking about
return function(){
console.log('hi my name is '+context.name)
}
}
}
let func = person.getSpeakFunction()
this is special the language decides the value of this, however context is not. Context will be whatever is assigned to it. It will not change unless you the programmer changes it.
so using the word _self, context, $this
or anything else when you assign the value of this to it.
it is 'locked in place' like any other regular variable.
let a = 2;
//this will never change
let _self = this //_self will never change as it's your variable
Now when you call your function and it looks for _self. It knows exactly what you are talking about.
It takes the value of this (which is determined by how the function is called) and stores it in a variable (which is still accessible in the closure (that will have a different value of this when it is called) that getConfig is returning).
This question already has answers here:
Javascript functions like "var foo = function bar() ..."?
(9 answers)
Closed 6 years ago.
Have a function assigned to a variable
var sq = function a(s){return s * s};
Now if i call sq(4) i am getting the result as 16 but if i try to call using the function name a(4) it throws an error "a is not defined"
Can we not call the function by its name once it is assigned to a variable.?
No, because you're using an assignment. You can just do var fn = function () { } or var fn = ()=> { } and get the same thing.
If you created the function and then assigned it to a variable, you could do both.
Basically,
function fn() {...}
var myFunc = fn;
You could then do both:
myFunc();
fn();
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
I have found the following code in a website .
var testModule = (function(){
var counter = 0;
return {
incrementCounter: function() {
return counter++;
},
resetCounter: function() {
console.log('counter value prior to reset:' + counter);
counter = 0;
}
};
})();
So it follows the syntax var a = (blah balh..)()
What does it actually mean? What is the meaning of variable declaration like a =()()..
It's defining a single-use function and executing it immediately. The code you provided is named the Module Pattern -- see here for more information about its properties: http://www.yuiblog.com/blog/2007/06/12/module-pattern/
A normal function might be created like this:
var f1 = function() {
console.log('bar');
};
And you could subsequently call it like so:
f1();
But in the example you provided, the function is both defined and executed once, and that function returns an object with two functions: incrementCounter and resetCounter. You can call them like so: testModule.incrementCounter() and testModule.resetCounter()
The Module Pattern is useful when you have a single object and you want to encapsulate some properties which are only available to the functions defined in the closure.
The anonymous function is executed and the return value is assigned to the variable.