Calling getFunction will return a unique function every time, right?
var getFunction = function() {
var myFunction = function() {
};
return myFunction;
}
var function1 = getFunction();
var function2 = getFunction();
function1 === function2; // false
Yes, every time a function is called, a new scope is created for that run and all variables defined in it are unique and not shared between runs of the function.
Even doing something like the following would have the same result as the inner function is still defined inside of the function's scope and can see the arguments to the outer function.
var getFunction = function() {
function myFunction() {
};
return myFunction;
}
var function1 = getFunction();
var function2 = getFunction();
function1 === function2; // false
This can be visualized as follows. The outer scope holds the three variable allocations and the getFunction invocations will create two new scopes which return a function object defined in that scope.
Related
i have a question, there is a problem with a function in a program that i was doing in javascript.
The function is supposed to work when you click on a paragraph, but when i click, the javascript console throws this: "Uncaught ReferenceError: donethingy is not defined
Line: 1".
JS:
window.onload = function(){
var thy = document.getElementById("thy");
var commanderIssue = document.getElementById("commanderIssue");
var listado = document.getElementById("thaCosa");
var thyLy = document.getElementsByTagName("p");
var nli;
var thyText;
var inserting = "a";
var commander = "b";
thy.onclick = function(){
inserting = "* " + prompt("Create a new item");
nli = document.createElement("p");
thyText = document.createTextNode(inserting);
nli.appendChild(thyText);
listado.appendChild(nli);
thyLy = document.getElementsByTagName("p");
}
thyLy.onclick = function donethingy(){
// thyLy.textDecoration.overline;
alert("done");
}
commanderIssue.onclick = function(){
alert("this thing is");
}
}
With the syntax you've used, the name donethingy doesn't actually become the name of the function because you are assigning the funciton's code directly to the onclick property of thyLy.
You could do this:
// This is a function declaration that associates a name with the function
function donethingy(){
// thyLy.textDecoration.overline;
alert("done");
}
// Then the function can be referred to or invoked by name
thyLy.onclick = donethingy;
But, when you create and assign the function in one statement, the function effectively becomes anonymous as it is stored and accessible via the property you assigned it to.
The decision to create a function declaration or an anonymous function requires you taking the following into account:
Anonymous functions can't easily be reused.
Anonymous functions can't easily be unit tested.
Named functions may require more memory, but can be reused and can be
easily unit tested.
You do not set variables or onclick properties to functions defined as:
obj.onclick = function <name>() {}
You set to anonymous functions, like you did for commanderIssue.onclick.
Just remove the name of the function to make it anonymous:
thyLy.onclick = function() {
alert("done");
}
It's good to remember that there are two ways of defining functions:
Declarations, which are executed when you invoke them:
function donethingy() { ... }
Expressions, which are executed when variable statements are executed:
thyLy.onclick = function() { ... }
How can I access a variable inside a function which is inside a function in javascript ?
var a;
var surveyObjects = Parse.Object.extend(surveyObject);
var query= new Parse.Query(surveyObjects);
query.count({
success: function(count){a = count;},
error: function(error){}
});
alert("count of function "+a);
a is showing undefined value. I need to use the value of a outside.
Because of how javascript, and most languages, scope variables, you can't access variables declared inside a function from outside a function. The variable belongs to the function's scope only, not the global scope.
Fortunately, functions inherit the scope of their caller. So the easiest way to make your variable accessible from outside the function is to first declare outside the function, then use it inside the function.
function one(){
var a;
function two(){
a = 10;
return a;
}
return a;
}
Note that you should be very careful about how you scope your variables. The whole point of functions is to encapsulate and isolate functionality.
In the case of promises, you can declare a variable outside the promise and then set its value on success.
var a;
Parse.doSomething().then(function(data) {
a = data;
});
EDIT: Based on what you showed in the comments, you're having async issues. Promises are asynchronous meaning they don't run in sequence in your code. That's why the success and error callbacks exist, to be called once the promise resolves. Your alert(a) is outside the promise callback, so it runs immediately, without waiting for the Parse promise to resolve so a is still undefined. If you put the alert(a) inside the promise callback, a will have been set by that point.
var a;
query.count({
success: function(count) {
a = count;
alert(a);
return a;
},
error: function(err) {}
});
// You can simply do it by
function test()
{
this.name='xyz';
}
var obj = new test();
console.log(obj.name);
You can do this by using implicit global variable behaviour.
function one(){
function two(){
a=10;
}
two();
}
one();
console.log(a);
If you don't declare a variable in javascript I.E not using the var keyword it becomes a global variable.
for further reading:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var#Implicit_globals_and_outer_function_scope
like it:
function one() {
this.two = function () {
var a = 10;
return a;
}
}
var o = new one();
alert(o.two());
use return statement to access variables globally.
function(){
var k=1;//local
return k;//global
}
result=k+10;//sample
Thanks.
I declared the variable as global and inserted value inside the inner function and then made a function call inside the function to trigger another function which call the value.
var a=0;
var surveyObjects = Parse.Object.extend(surveyObject);
var query= new Parse.Query(surveyObjects);
query.count({
success: function(count) {a =count; total();},
error:function(error){}
});
function total(){alert (a);}
I'm trying to learn some OOP, so bear with me. I need to use a variable I defined in one function, elsewhere. Here is my example code (I want INTERCEPT!! to be logged, but it returns undefined):
function Talk() {
var greeting;
var pleaseStop; // declare it
this.A = function () {
greeting = 'hello';
console.log(greeting);
var intercept = function () {
pleaseStop = 'INTERCEPT!';
}
}
this.B = function () {
greeting = 'goodbye';
console.log(pleaseStop); // this returns undefined!
console.log(greeting);
}
}
var activateTalk = new Talk();
activateTalk.A();
activateTalk.B();
This whole code logs the following:
hello
undefined
goodbye
I have also tried intercept.pleaseStop() but it still returns undefined. Would anyone know of a solution?
EDIT:
I've removed the var the second time, but it still returns undefined:
http://jsfiddle.net/d654H/2/
var pleaseStop = 'INTERCEPT!';
You're declaring a new, function-local variable here; drop the var to assign to the existing variable in scope.
Then, you need to actually call intercept; at the moment you only define it.
It's your choice as to when you call that function; in this live example I simply do so immediately after the definition, for the purposes of exposition.
Remove var in front of the assignment to pleaseStop.
This assigns a new value to the pleaseStop declared inside the constructor, which is visible also from inside B:
var intercept = function () {
pleaseStop = 'INTERCEPT!';
}
This declares a new local variable pleaseStop, completely unrelated to the other pleaseStop, that is not visible outside intercept:
var intercept = function () {
var pleaseStop = 'INTERCEPT!';
}
If you do the latter instead of the former, you end up changing the value of another variable than the one you intended.
Your problem is you never set pleaseStop. You have declared intercept as a function, but you never called it. Therefore, pleaseStop is undefined.
Firstly you have't called intercept() anywhere and also u did something
var pleaseStop = 'INTERCEPT!';
which will create new variable instead of initializing global variable
You can do something like this
function Talk() {
var greeting;
var pleaseStop; // declare it
this.A = function () {
greeting = 'hello';
console.log(greeting);
var intercept = function () {
pleaseStop = 'INTERCEPT!';//changed
}
intercept(); //..Added
}
this.B = function () {
greeting = 'goodbye';
console.log(pleaseStop); // this returns undefined!
console.log(greeting);
}
}
var activateTalk = new Talk();
activateTalk.A();
activateTalk.B();
Without var keyword.
var pleaseStop = "A";
function foo(){
pleaseStop = "B"; // overwriting to "B"
}
foo();
alert(pleaseStop); // shows "B"
With var keyword.
var pleaseStop = "A";
function foo(){
var pleaseStop = "B"
// This defines a new variable 'pleaseStop'
// in the scope of function foo(){}.
}
foo();
alert(pleaseStop); // shows "A"
Variable Scope
JavaScript has function-level scope. In most languages which have block-level variable scope, variable are accessible whithin their block surrounded by curly brackets ({and}). But JavaSciprt doesn't terminate scopes at the end of blocks, but terminate them at the end of functions.
I'm sure there are many articles and documents about it. I googled it and found an intresting introductory article.
http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
Hope this helps.
In javascript, I have an object containing a function and want to add to it a private member.
How can I do that?
function function1 () {
var function2 = function () {
console.log("This is an actual function.");
}
function2.publicMember = 5;
function2.privateMember = 7;
return function2;
}
I want privatMember to be inaccessible to the user of function1.
I found this question but I can't quite translate it to my situation because my object is a function:
How to add private variable to this Javascript object literal snippet?
thanks!
Wrap it into one more function to create new scope (i.e. using iife):
function function1 () {
var function2 = (function(){
var privateMember = 7;
return function () {
privateMember ++; // do something with really private member
console.log("This is an actual function.");
}
})();
function2.publicMember = 5;
return function2;
}
Declare the vars inside the function that needs access to them:
function function1 () {
var publicMember = 5;
var function2 = function () {
var privateMember = 7;
console.log("This is an actual function.");
}
return function2;
}
So function2 can see the vars inside its own closure (privateMember) and any parent scope.
I want to use JQuery in a Javascript program I'm working on but I ran into some issues with scope. How do I call myfunction2 from myfunction1 in this psuedo-code? (assume that a new MyConstructor object has been created somewhere and that myfunction1() has been called)
function MyConstructor(){...}
MyConstructor.prototype.myfunction1 = function(param) {
$('#some_element').click(function(){
this.myfunction2('clicked!'); //this doesn't work
});
}
MyConstructor.prototype.myfunction2 = function(param) {
}
myfunction2 can be called with this.myfunction2() when in any function of MyConstructor.
In your case you are trying to call myfunction2 inside another function that has a different meaning for this. To access myfunction2 you can create a variable for either this or this.myfunction2 that is in closure scope that extends to the function parameter of click
var self = this;
$('#some_element').click(function(){
self.myfunction2('clicked!');
});
or
var myfunction2 = this.myfunction2;
$('#some_element').click(function(){
myfunction2('clicked!');
});