Skip to content

Instantly share code, notes, and snippets.

@hemantajax
Created May 26, 2012 12:38
Show Gist options
  • Save hemantajax/2793800 to your computer and use it in GitHub Desktop.
Save hemantajax/2793800 to your computer and use it in GitHub Desktop.
this magic, what is this
<!doctype html>
<head>
<meta chrset="UTF-8" />
<title>How "this" works</title>
</head>
<body>
<a href="http://www.google.com">Hit me baby</a>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
(function($){
//1: Window object
console.log("1: Window object");
console.log(this);
//2: this refers to anchor that was clicked
function doIt(e){
console.log("2: this refers to anchor that was clicked");
console.log(this);
e.preventDefault();
}
$("a").on("click",doIt);
//3:
function doThat(){
console.log("3: this refers to Window object");
console.log(this);
}
$("a").on("click",function(e){
doThat();
e.preventDefault();
});
//4:
var obj={
doIt:function(e){
console.log("4: this refers to anchor that was clicked");
console.log(this);
e.preventDefault();
}
};
$("a").on("click",obj.doIt);
//5: change this context using $.proxy
var obj1={
name:"Hemant",
doIt:function(){
console.log("5: this refers to obj1 now");
console.log(this);
console.log("my name is "+this.name);
}
};
$("a").on("click",$.proxy(obj1.doIt,obj1));
//6: this refers to obj2
var obj2={
doIt:function(){
console.log("6: this refers to obj2 now");
console.log(this);
}
};
$("a").on("click",function(e){
obj2.doIt();
e.preventDefault();
});
//7: this refers to anchor that was clicked
var obj3={
doIt:function(){
console.log("7: this refers to anchor that was clicked");
console.log(this);
}
};
$("a").on("click",function(e){
obj3.doIt.call(this);
e.preventDefault();
});
})(jQuery);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment