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();
Related
Is there a difference between
function test(){
var myVar;
}
and
function test(){
this.myVar;
}
The value of this is determined by how function is called whereas var VARIABLE_NAME will create a variable in the local-scope of the function.
In second example, you are creating Object-Constructor using which you can create many instances of the test object using new operator
function test(name) {
this.name = name;
}
console.log(new test('Abc'));
console.log(new test('Xyz'));
There are two scopes in javascript , local or function scope and global scope .
In your case this is global and var is local scope/function scope .
If you use this inside IIFE (immediate invoking function expression)and 'use strict' its not global
The most difference is that your first code works like a private property (local scope) and the second is like a public property (global scope).
Examples:
var test = function(){
this.myVar = "test var";
}
var test2 = function() {
var myVar = "test2 var";
}
alert((new test()).myVar);
alert((new test2()).myVar);
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()
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.
I don't mean a name property, e.g
String.prototype.myFunc = function(){}
var myString = new String();
console.log(myString);
When you view the created function in the console, there is a name:''. I was wondering how we set this.
Use a named function:
String.prototype.myFunc = function myFunc(){};
You can construct a function with a function declaration statement and then assign it to the prototype property of your choice:
(function() { // to keep the global scope clean
function myFunc() {
// whatever
}
String.prototype.myFunc = myFunc;
})();
You can in fact give a name to any function in a function instantiation expression, but it's not a super-safe thing to do.
You did you an anonymous function, whose name property is the empty string.
Either use a named function expression:
String.prototype.myFunc = function myNamedFunc(){};
or assign a function which you declared with a name:
function myNamedFunc() {};
String.prototype.myFunc = myNamedFunc;
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;
}
}