Closure vs Global Variable

Benchmark created on


Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<a href="#" id="element">Click me</a>

Test runner

Ready to run.

Testing in
TestOps/sec
Closure
var obj = {
 init: function() {
  var self = this;
  $('#element').click(function() {
   self.clickEvent();
  });
 },
 clickEvent: function() {
  this.miscMethod();
 },
 miscMethod: function() {}
};
obj.init();
$('#element').click();
ready
Global variable
var obj = {
 init: function() {
  $('#element').click(this.clickEvent);
 },
 clickEvent: function() {
  obj.miscMethod();
 },
 miscMethod: function() {}
};
obj.init();
$('#element').click();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.