Dimitri Kouvdis
Dimitri Kouvdis

Reputation: 121

What this JavaScript function method called?

I am quite interested when I run this simple function

$(window).resize(function() {
    var that = $(this);
    var widthValue = that.width();

    console.log(widthValue + 'px');
});

It works when I start resizing my browser window.

But when I do this

$(window).resize(function() {
    var that = $(this);
    var widthValue = that.width();

    console.log(widthValue + 'px');
}).resize();

It acts like load();. I added resize() at the end.

What is this called? Not sure I understand why and how this works.

Upvotes: 0

Views: 79

Answers (2)

Quentin
Quentin

Reputation: 943643

The technique is called Chaining.

It boils down to a function returning this at the end, so you can call another method of the same object by chaining the method calls one after the other.

var foo = {
  count: 0,
  up: function () { this.count++; return this; },
  show: function () { alert(this.count); return this; }
}

foo.show().up().show().up().up().show();

In this particular example, the resize method is overloaded. If you give it a function argument then it will bind that function as an event handler. If you call it without arguments, then it will trigger that event instead.

Upvotes: 5

Daniel A. White
Daniel A. White

Reputation: 190942

With the 2nd case, you are invoking or triggering the resize event.

Upvotes: 0

Related Questions