I have this....
function MyFunction() {
var myVar = "I think I am encapsulated";
this.getMyVar = function() {
return myVar;
}
}
var myProperty = new MyFunction();
console.log(myProperty.getMyVar());
myProperty.myVar = "you're not encapsulated";
console.log(myProperty.getMyVar());
It outputs: "I think I am encapsulated twice". Why? I did not think this was a closure...
The closure is around the "getMyVar" function. The variable "myVar" inside the constructor is a local variable, and not visible outside the function except as the return value from "getMyVar".
Setting a "myVar" property on the object does just that, but the "getMyVar" function is not returning a property of an object; it's returning the value of the local variable in the closure.
Yes, it is.
When you define a function inside of another function, the inner function has access to all of the outer function's local variables...
In your case, getMyVar has access to myVar - through the closure.
var myVar = "I think I am encapsulated";
this.getMyVar = function() {
return myVar;
}
This is a closure, and the myVar variable from the time the function was created will be returned. Notice that's it a local variable, so there's no other way to access it after this function exits.
var myVar = "I think I am encapsulated";
Notice that this is not this.myVar (the variable you're setting later with myProperty.myVar).
Probably what you're trying to do is:
function MyFunction() {
this.myVar = "I think I am encapsulated";
this.getMyVar = function() {
return this.myVar;
}
}
Related
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);}
Here I'm trying to use a variable in function New(), the variable was created in the function Test().
I'm still a bit confuse about how to use global variable.
function New(){
Test();
//this show nothing
alert(myName);
}
function Test() {
myName = "John";
}
New();
Even when I do "var myName;" outsise of these functions, it doesn't work.
Still searching
Check this fiddle
things to change :
1) use function New(){} instead of function New{}
2) return myName from test function and store it in new variable in New function
function New(){
var myName= Test();
//this show nothing
alert(myName);
}
function Test() {
var myName = "John";
return myName
}
New();
update : yeah u can also define myName as global variable and use it
When you want to declare a variable for use, use the var keyword. When you do this, the location of where you do it determines the "scope" of the variable. If you want to use the variable in two functions, you can simply declare the variable outside of both:
var myVariable = "Something";
function1(){
myVariable = "something else";
}
function2(){
myVariable = "something else again";
}
Another way to share data is to pass that data as arguments into a function:
function1(){
var myVariable = "Something";
function2(myVariable);
}
function2(someName){
alert(someName); // "Something"
}
In your case, you didn't use the "var" keyword to declare your variable, so it became global, but you have a typo in your code, so it didn't run.
Its just a small type error. Just add braces after New
var myName; // have myName global ie, outside all functions
function New(){ // needs the braces() for New to be a function
Test();
alert(myName);
}
function Test() {
myName = "John";
}
New();
Declare myName globally, then define myName in the return of Test() function. When declaring a function, always use keyword "function", "()", and "{}" no matter what.
var myName;
function New() {
alert(Test());
}
function Test() {
myName = "John";
return myName;
}
New(Test);
Global variable is something whose scope is for a particular class and not restricted to a function.
You can create variable myName inside class but outside function and use it anywhere within class.
var myName="";
function New{
Test();
//this show nothing
alert(myName);
}
function Test() {
myName = "John";
}
New();
how can I declare,set and access global variable from one function to another?
var testvar;
$(document).ready(function(){
test1();
});
function test1(){
return testvar;
}
function test2(){
var a = "Hellow World";
testvar = a;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The code above was just my sample to make it easy to understand on what I am trying to do. This is just for educational purposes. I just want to get the result in that way. Or is there a way to set a Global variable within a function and use it to another function outside that function?
What do to?
Creating variables in the Global scope is very bad practice. You shouldn't do it because it can cause conflicts especially in future JavaScript versions.
You can run the functions from a scope or object, try:
var shared = {};
$(document).ready(function () {
test1.call(shared);//undefined
test2.call(shared);
test1.call(shared);//foo
});
function test1 () {
alert(this.testvar);
}
function test2 () {
var a = 'foo';
this.testvar = a;
}
How it works
In simple terms, this will store all the variables in the object (shared). You can declared a "shared variable" by using this. instead of var. By using .call() we can choose to run the function in the scope of the object. I'm not the best at explaining, learn more here
Fiddle
Global Variables are always accessible from everywhere. But this might help you understand it better:
var testvar;
$(document).ready(function(){
console.log(testvar); // outputs: undefined
test2();
console.log(testvar); // outputs Hello World
console.log(test1()); //outputs Hello World
});
function test1(){
return testvar;
}
function test2(){
var a = "Hellow World";
testvar = a;
}
var testvar;
$(document).ready(function(){
test1();
});
function test1(){
return test2();
}
function test2(){
var a = "Hellow World";
testvar = a;
}
console.log(testvar);
test2() is not called. It needs to be called in order to redeclare the variable
https://jsfiddle.net/uwzapwrk/
I use this method and it works for me
function somefunctionname(){
// Some action
anotherfunctionname(put_your_value);
}
function anotherfunctionname(put_parameter_as_you_want){
var some_var = put_parameter_as_you_want;
// Some action with your var
}
This method work after somefunctionname() was execute and you can execute the anotherfunctionname() with variable was store on somefunctionname()
var variable = "before";
change();
alert(variable);
function change(){
variable = "after";
}
Does in possible to change global variable inside function without return ? I need after call function change have output "after"
Yes, it is possible, but remember to NOT put the var keyword in front of it inside the function.
ERORR - DOES NOT WORK:
var variable = "before";
change();
alert(variable);
function change() {
var variable = "after";
}
WORKS:
var variable = "before";
change();
alert(variable);
function change() {
variable = "after";
}
You should avoid declaring global variables since they add themselves as properties to the window. However, to answer your question, yes you can change global variables by setting either changing variable or window.variable.
Example:
http://jsbin.com/xujenimiwe/3/edit?js,console,output
var variable = "before"; // will add property to window -- window.variable
console.log(variable);
change();
console.log(window.variable);
function change(){
variable = "after"; // can also use window.variable = "after"
}
Please let me know if you have any questions!
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.