debounce in JavaScript

4/06/2011

I ran into a situation recently where a function would get executed repeatedly after given timeout. I wanted to make sure that only last execution was taken into the consideration and I came up with:

function debounce(fn, wait) {
  var timeout = null;
  return function () {
    clearTimeout(timeout);
    var args = arguments;
    var ctx = this;
    timeout = setTimeout(function () {
      fn.apply(ctx, args);
    }, wait);
  }
}

now I can use it like this:

function print(value) {
  console.log(value);
}

var printD = debounce(print, 100);
printD(1);
printD(2);
printD(3);

With this approach only last call will get executed with the value 3.

No Comments

prototype, [[Prototype]], __proto__, constructor in JavaScript

7/05/2011

prototype, [[Prototype]], __proto__, constructor can be confusing. Here are a few notes which I’m writting mostly for myself but maybe it will help somebody else:

prototype from the Function point of view:

  • every function has access to a publically available prototype property:
function Foo() {}
console.log(Foo.prototype); //Object
  • the value of the prototype property references a prototype object
  • the prototype object contains an attribute called constructor. The value of the constructor attribute references the function itself when the function is orginally created.
console.log(Foo.prototype.constuctor === Foo); // true

prototype from the object point of view:

  • every object has access to prototype object
  • the prototype is not publicly accessible from the object. The object has an implicit access to the prototype via internal [[Prototype]] property
  • when object is created the value of the [[Prototype]] implicitly references the same object as prototype property of the constructor function
// pseudo code
var foo = new Foo();
foo.[[Prototype]] => Prototype <= Foo.prototype
  • some implementations expose a public attribute on objects called __proto__ which can be used to access prototype object
  • (You should never relay on __proto__ since it’s not a standard. I’m using it here for demo purposes.)

console.log(foo.__proto__ === Foo.prototype) // true
  • it’s important to mention that if the value of the prototype attribute attached to the function changes, the object created before the change happens will still point to the old Prototype object.
Foo.prototype = {};
console.log(foo.__proto__ === Foo.prototype) // false

Here are few more examples which illustrate it:

Please check this exceptional article written by Dmitry A. Soshnikov if you want to learn more about the topic.

No Comments

object literals chaining via prototype in JavaScript

27/02/2011

Recently I played with the idea of chaining object literals via prototype. Here is what I came up with:

function chain() {
  var cur = null,
        prev = null;
  for (var i = l = arguments.length - 1; i >= 0; i--) {
    prev = cur;
    cur = (function(params) {
      return function() {
        for (var param in params) {
          this[param] = params[param];
        }
      }
    })(arguments[i]);
    if (i < l) {
      cur.prototype = new prev;
    }
  }
  return new cur;
}

and an example usage:

var a = {a: 1}, b = {b: 2}, c = {c: 3},
var chained = chain(a, b, c);
console.log(chained.c); // 3
No Comments

Creating new objects in JavaScript

12/01/2011

I’m writing this to remind myself about what happens when new object is constructed in JavaScript. This is based on the knowledge I have so far. Please let me know if you find something which is not correct.

Every object in JavaScript has a property called [[Prototype]] which is hidden and not accessible. The exceptions are functions which are also objects in JavaScript. Each function has an additional public property called prototype.

This property is used when setting up a prototypal inheritance. It’s important to mention that public prototype property is not equal to the private hidden [[Prototype]] property.

In order to create a new object of the specific type the constructor has to be defined first. In JavaScript constructors are just regular functions. For example:

// function which will be used to construct new object (constructor)
function Foo() {}

A new object can be created with the operator ‘new’:

// new object is created
var foo = new Foo;

The operator ‘new’ in the line above does a few things:

1) it creates a new object with the [[Prototype]] property
2) the [[Prototype]] property of the newly created object is set to the prototype of the function used as a constructor to create the object. This sounds complicated but it’s actually pretty simple. Let’s take a look at this code:

// __proto__ is a visible  
// in some browsers (Chrome, Safari, FF)
// and it's deprecated now: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/proto
// the [[Prototype]] property is set to the prototype of the constructor (function)
console.log(foo.__proto__ === Foo.prototype) // true

3) The newly created object is passed to Foo() as the implicit parameter ‘this’
4) The object ‘this’ is returned and assigned to the variable foo

Foo’s public prototype property is an object itself and has access to it’s own [[Prototype]] property. On top of that it also has an extra property called constructor which points back to function Foo.

We can test it with:

console.log(Foo.prototype.constructor === Foo) // true

Thanks to the prototypal nature of JavaScript we can access the properties of the Foo’s prototype directly from foo. Since we alredy know that:

console.log(foo.__proto__ === Foo.prototype) // true

and:

console.log(Foo.prototype.constructor) // Foo

based on the above we know that:

console.log(foo.constructor === Foo.prototype.constructor) // true

What actually happens when we try to access constructor property from foo is that first the runtime looks up the property on the object foo level and it doesn’t find it:

console.log(foo.hasOwnProperty('constructor')) // false

then it looks up the property in the object referenced by [[Prototype]] property.
Since in this case we know that the [[Prototype]] of foo points to the public prototype property on Foo, the constructor is present and visible.

Here are the tests together:

function Foo() {}
var foo = new Foo;
console.log(Foo.prototype.constructor === Foo) // true
console.log(foo.__proto__ === Foo.prototype) // true
console.log(Foo.prototype.constructor) // Foo
console.log(foo.constructor === Foo.prototype.constructor) // true
console.log(foo.hasOwnProperty('constructor')) // false
No Comments

JavaScript closures

25/06/2010

For given content:

  <div id="test0">change me</div>
  <div id="test1">change me</div>
  <div id="test2">change me</div>
  <div id="test3">change me</div>

The code:

 for (var i = 0; i < 4; i++) {
   $('#test' + i).click(function(){
     $(this).html(i);
   });
}

will print (every time any of the elements is clicked):

4
4
4
4

Here is how this could be solved with the closure:

  for (var i = 0; i < 4; i++) {
    (function (i) {
      $('#test' + i).click(function () {
        $(this).html(i);
      });
    })(i);
  }
No Comments

JQuery 1.3

15/01/2009

New release contains new selector engine called Sizzle (the fastest css selector out there) and live events (which work similar to the live query plugin).

More details can be found here

No Comments

Peppy fast css3 selector engine

28/10/2008

Peppy is a small and very fast css3 selector written by James Donaghue. Here is how you can use it:

var selector = "div";
var context = "#elementId";
var q = peppy.query(selector, context);
No Comments

JavaScript closures

16/09/2008

Nice presentation about JavaScript closures posted by Stuart Langridge

No Comments