I recently working on a JavaScript project, which required to write class.

Usually I just use 3rd party plugin for most of my project, e.g. jQuery.ajax

1
2
3
4
5
$.ajax({
url: ...,
success: function (data, textStatus, jqXHR) {
}
});

something like that, but when I try to create a class which has a method like success in jQuery.ajax, to let the user who use my library to be able to handle the callback. So here is what I found:

FooBar.js

Your defination goes here

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
(function() {
this.FooBar = function() {
initializeEvents.call(this);
}

FooBar.prototype.close = function() {
// this will invoke the method that defined in the implementation script
this.options.close.call(this);
}

function initializeEvents() {
if (this.closeButton) {
this.closeButton.addEventListener('click', this.close.bind(this));
}
}
});

script.js

Your implementation goes here

1
2
3
4
5
var foobar = new FooBar({
close: function() {
alert('you clicked on close button');
}
});

If let say you want to pass extra params

1
2
3
4
5
6
7
this.options.close.call(this, 'extra message');

---

close: function(msg) {
alert('you clicked on close button with ' + msg);
}

References: