Last active
December 16, 2015 17:08
-
-
Save rizalp/5467800 to your computer and use it in GitHub Desktop.
Javascript: Scope
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*In JavaScript, functions are the only things that create a new scope*/ | |
var globalVar = "This is a global variable."; | |
var globalFunction = function() { | |
var localVar = "This is a local variable."; | |
var localFunction = function() { | |
var localVar = "hello, world!"; | |
alert(localVar); | |
}; | |
localFunction(); | |
alert(localVar); | |
}; | |
globalFunction(); | |
var g = "global"; | |
function go() { | |
var l = "local"; | |
} | |
go(); | |
alert(l); // throws a reference error | |
//JavaScript uses the this keyword to get a reference to the current execution context. | |
function go() { console.debug(this); } | |
go(); //gives you a reference to the top-level execution context; in a browser, that’s the browser window itself. | |
var myObject = { | |
go: function() { | |
console.debug(this); | |
} | |
}; | |
myObject.go(); // console.debugs a reference to myObject | |
//when using functions as constructors, you see the same behavior: | |
function MyClass() { | |
this.go = function() { | |
console.debug(this); | |
} | |
} | |
var instance1 = new MyClass(); | |
var instance2 = new MyClass(); | |
instance1.go(); // console.debugs a reference to the MyClass instance1 | |
instance2.go(); // console.debugs a reference to the MyClass instance2 | |
//JavaScript functions have two methods available to them that are of particular interest for handling context. Let’s look at call: | |
showCount.call(products, 4); | |
//Apply is very similar but is used when you don’t know how many arguments you will be passing. It takes an array as its second parameter: | |
showCount.apply(products, [4]); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment