Skip to content

Instantly share code, notes, and snippets.

@jgautier
Created May 23, 2011 03:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgautier/986206 to your computer and use it in GitHub Desktop.
Save jgautier/986206 to your computer and use it in GitHub Desktop.
Javascript Scoping
function Button(text){
this.text = text;
}
Button.prototype.onClick=function(callback){
//set fake x,y coordinates
var x=0,y=0;
callback.apply(this,[x,y]);
};
var button = new Button('The Button');
button.onClick(function(x,y){
//can access the text pass into the constructor
console.log(this.text);
console.log(x);
console.log(y);
});
function Button(text){
this.text = text;
}
Button.prototype.onClick=function(callback){
//set fake x,y coordinates
var x=0,y=0;
//get a bound function
var boundCallback = callback.bind(this,x,y);
//call it
boundCallback();
};
var button = new Button('The Button');
button.onClick(function(x,y){
//can access the text pass into the constructor
console.log(this.text);
console.log(x);
console.log(y);
});
function Button(text){
this.text = text;
}
Button.prototype.onClick=function(callback){
//set fake x,y coordinates
var x=0,y=0;
callback.call(this,x,y);
};
var button = new Button('The Button');
button.onClick(function(x,y){
//can access the text pass into the constructor
console.log(this.text);
console.log(x);
console.log(y);
});
function Button(text){
this.text = text;
}
Button.prototype.onClick=function(callback){
//set fake x,y coordinates
var x=0,y=0;
callback(x,y);
};
var button = new Button('The Button');
button.onClick(function(x,y){
//cannot access the text pass into the constructor
console.log(this.text);
console.log(x);
console.log(y);
});
var scope1 = function(){
//scope 1
var scope2 = function(){
//scope2 creates a new scope and has access to scope1
var scope3 = function(){
//scope3 creates a new scope ans has access to scope2 and scope3
}
}
}
function localScope(){
var localVariable = "local";
}
//create a new local scope object
var newLocalScope = new LocalScope();
//does not exist
console.log(newLocalScope.localVariable);
var noVar = function(){
x = 1;
}
noVar();
//1
console.log(x);
var withVar = function(){
var y = 1;
}
withVar();
//not defined
console.log(y);
function thisObject(){
//create variable and put it in the current execution context
this.thisVariable = 'this';
}
//create an instance of the object
var thisInstance = new thisObject();
//has access to any variable bound to this
console.log(thisInstance.thisVariable);
var scope1 = function(){
//create a variable in scope1
var variableInScope1=0;
var scope2 = function(){
//override the variable in scope2
var variableInScope1=1;
//variableInScope1 will now reference 1 not 0!
}
}
function noVar(){
x = 1;
}
//set x
noVar();
console.log(x);
//also 1
console.log(window.x);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment