Reputation: 33174
(purely for learning purposes) we are implementing a few features of JQuery and would like to know how to wrap the code in an IIFE ("module").
The two JQuery methods we are trying to implement are addClass and removeClass and we need to be able to chain these methods.
Currently our code works:
var FAQuery = function(selector) {
this.id = selector.replace('#','');
this.elem = document.getElementById(this.id);
this.addClass = function(className) {
this.elem.className = this.elem.className + className;
return this;
}
this.removeClass = function(className) {
this.elem.className = this.elem.className.replace(className, '');
return this;
}
return this;
}
which is then invoked in the following way:
FAQuery('#div3').addClass('pass').removeClass('fail');
How would we go about wrapping this in an IIFE?
Try it: http://morning-challenge.herokuapp.com/20150519.html
Full code with browser-based unit tests: http://git.io/vTcRL
Thanks!
Upvotes: 2
Views: 328
Reputation: 69964
IIFE's are used to force variables to be local instead of global. However, you are already exporting just the variable you want so there is not much an IIFE would do here.
That said, one thing I could recommend would be to put the methods on the "prototype" instead of attaching them to every instance.
var FAQuery = function(selector) {
if(!(this instanceof FAQuery)){
return new FAQuery(selector);
}
this.id = selector.replace('#','');
this.elem = document.getElementById(this.id);
}
FAQuery.prototype.addClass = function(className) {
this.elem.className = this.elem.className + className;
return this;
}
FAQuery.prototype.removeClass = function(className) {
this.elem.className = this.elem.className.replace(className, '');
return this;
}
I also added a line with an instanceof check so you don't need to use the new
operator when creating an FAQuery object.
Upvotes: 1