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.
I have three simple programs below with different outputs. I am a bit confused as to why I get a different output. What really happens when you assign a function to a variable? Does it not run unless you have parentheses (i.e. myfunction())? I'm also very confused as to how JavaScript allows the parenthesis behind a function as 'optional' when calling it. Can someone clear this up? I only know Java so this is all new territory for me.
// ------First--------------------------------
var x = 9;
function myfunction (){
x = 3;
}
var w = myfunction;
w();
console.log(x);
//output is 3
// ---------Second -----------------------------
var x = 9;
function myfunction (){
x = 3;
}
var w = myfunction;
console.log(x);
//output is 9
// ---------Third -----------------------------
var x = 9;
function myfunction (){
x = 3;
}
var w = myfunction();
console.log(x);
//output is 3
No, it does not. A reference to a function by name is simply a reference to a value, like any other value. Without the () operator, it's not a function call.
Parentheses are not optional when calling a function except when it's being called via the new operator. Thus:
function foo() {
console.log("hi!");
}
var otherFoo = foo; // no function call
var obj = new foo; // function call via "new"
var x = foo(); // function call via "()"
I understand the general idea behind the this keyword but I'm having trouble figuring out what it actually refers to in practice. For example, in both these example exercises, I guessed the wrong number.
for question1, I said that the alert would be '5', because it is referring to the this.x outside the anonymous function in the function.
In question2, I thought the alert would be 5 because this line
var alertX = o.alertX;
would bind the value 5 for property x inside the variable o to the new variable 'alertX' which becomes the function call in the next line: alertX();
Can you explain why I'm wrong?
var question1 = function() {
this.x = 5;
(function() {
var x = 3;
this.x = x;
})();
alert(this.x);
};
var answer1 = 3;
var question2 = function() {
this.x = 9;
var o = {
'x':5,
'alertX':function() { alert(this.x); }
};
var alertX = o.alertX;
alertX();
}
var answer2 = 9;
In the first case, when you invoke a method with no explicit receiver this is the Global object (the window in a web browser).
Similarly in the second case: even though the function is defined on the object, and you are inside another, by invoking the function with alertx() the this is set to the Global/window.
In short:
For foo.bar(), the this inside of bar will be foo.
For bar(), the this will be the Global object.
This includes so-called "self-invoking lambdas", i.e. (function(){ ... })().
For bar.call(whee) and bar.apply(whee), the this will be whee (because that's what these methods do).
Another example:
var o1 = { name:"o1", f:function(){ console.log(this.name) } };
var o2 = { name:"o2" };
o2.gogogo = o1.f;
o2.gogogo(); // Will output "o2"
These are good examples of how interesting this becomes in Javascript. this always refers to the context in which it was invoked / called, not simply where it is at that moment! question2 is a perfect example of it.
I'm assuming you are invoking these globally like so:
question1();
question2();
In question1:
You have an anonymous function that is ran after you first set x to 5. This anonymous function if not set to a variable, inside a function etc, would have this set to the global variable of window. But you have it within a function & set to variable question1. So when it runs itself, it sets this's (which is question1 function) x variable to 3.
In question2:
X is originally set to 9, this being question2 in this instance. Now the part that is throwing you off is that, even though within the o {} object you set x : 5. And your alertX function is calling this.x. All of this would lead you to think it will alert 5! But you are invoking your alert function outside of the o {} object, hence the this refers to question2 function again!
Put the following into your browser's console
var x = -1, log = function(){ // set up some stuff
if(console) if(console.log) return console.log.apply(console, arguments),undefined;
return alert(arguments.join(', ')),undefined;
},
question1 = function() {
this.x = 5; // question1.x is 5
(function() { // anonymous function fires in global 'window'
var x = 3; // so window.x is now 3
this.x = x; // this is window
})();
log('ans1',this.x,this); // see below
},
question2 = function() {
this.x = 9; // question2.x is 9
var o = {
'x':5, // o.x is 5
'alertX':function() { log('ans2',this.x,this); }
};
var alertX = o.alertX; // alertX === o.alertX
alertX(); // being called in global scope
// to make alertX have scope of question2
this.alertX = o.alertX; // this is question2
this.alertX(); // so we're calling from question2
},
a1 = new question1(), // note the new operator
a2 = new question2();
undefined;
And you'll get
ans1 5 question1
ans2 3 Window
ans2 9 question2
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Return Global Variable from Javascript Method
I have this.
var thisData = "";
function calculateThings(newData) {
thisData = newData.things.otherthings //has a value of 10;
}
alert(thisData) //returns nothing
What am I doing wrong?
you need to call your function:
calculateThings(newData);
should be more like:
var thisData = "";
function calculateThings(data) {
thisData = data.things.otherthings //has a value of 10;
}
calculateThings(newData);
alert(thisData) //returns nothing
where data is your parameter, and you can pass whatever you want into it.
You created a function but never call it. You need to call it via:
var thisData = "";
function calculateThings(newData) {
thisData = newData.things.otherthings //has a value of 10;
}
alert(calculateThings(thisData));
or you can self-invoke the function like:
(function calculateThings(newData) {
thisData = newData.things.otherthings //has a value of 10;
})()
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Get property of object in JavaScript
var Terminal = function() {
this.walk = function() {
alert('hello');
}
this.go = 'walk';
this.move = 'walk';
}
var term = new Terminal();
var fn = 'walk';
if (term.hasOwnProperty(fn)) {
term.{fn};
}
How can I run the method term.walk() using the string 'walk'?
There are a couple of ways. The simplest is
term[fn]();
Or alternatively
var funcObj = term[fn];
funcObj.apply(term);
Use term[fn] to access the <fn> property of term.
All properties can be accessed using object["propertyname"]. Globally defined properties/methods can be called through window["propertyname"].
There's only one occasion where variables cannot be accessed through obj["prop_name"]:
function foo(){
var bar = 759;
//There is no "obj" where obj.bar exists.
}