728x90
12_Scope.html
<script>
// [Global Scope]
// In a browser, the global scope is the window object.
// If a variable declaration occurs outside of a function,
// then that variable exists on the global object.
// it could be referenced as window.x,
// but because it exists on the global object we can simply refer to it as x.
var x = 9;
//[Local Scope]
//JavaScript also creates a Local Scope inside each function body
function myFunc(){
var y=5;
}
//console.log(y); //ReferenceError: y is not defined
//if you declare a variable and forget to use var keyword.
//that variable is automatically made global.
(function(){
z=10;
})();
console.log(z);
//Wrapping everything in a function which is then immediately invoked means
//all the variables within that function are bound to the local scope.
//At the very end you can then expose all your methods by binding
//the jQuery object to the window, the global object.
(function(){
var jQuery = {/*All my methods go here */};
window.jQuery = jQuery;
})();
function outer(){
var x = 5;
function inner(){
console.log(x);
var y = 10;
}
inner(); //5
//console.log(y); // ReferenceError: y is not defined
}
outer();
//Functions have access to variables defined in the same scope.
var foo = "hello";
var.sayHello = function(){
console.log(foo);
};
sayHello(); //"hello"
console.log(foo); //"hello"
//Variable with the same nama can exist in different scopes with different values:
var foo = "world";
var sayHello = function(){
var foo = "hello";
console.log(foo);
};
sayHello(); //"hello"
console.log(foo);//"world"
//When, within a function, you reference a variable defined in an outer scope,
//that function can see changes to the variable's value after the function is defined.
var myFunction = function() {
var foo = "hello";
var myFn = function() {
console.log( foo );
};
foo = "world";
return myFn;
};
var f = myFunction();
f(); // "world"
(function() {
var baz = 1;
var bim = function() {
console.log( baz );
};
bar = function() {
console.log( baz );
};
})();
bar();
//bim(); //bim is not defined outside of the function
//console.log( baz ); // baz is not defined outside of the function
</script>
728x90
'JS > JavaScript' 카테고리의 다른 글
[JQuery] [ajax] 04. ajaxMethod (0) | 2017.08.28 |
---|---|
[JS] 13. Closure (0) | 2017.08.28 |
[JS] 11. This (0) | 2017.08.28 |
[JS] 10. TypeOf (0) | 2017.08.28 |
[JS] 09. Function (0) | 2017.08.28 |
댓글