Can someone explain to me the reason why this function needs the $this variable in this js function?
var $ = function(selector){
var classexp = /^\.(.*)/;
var idexp = /^\#(.*)/;
//assign instance to private property
var $this = this;
//define element property for selector
this.el;
//if true
if( selector.match(classexp) ){
//get class name and find elements by it
var match = classexp.exec(selector);
this.el = document.getElementsByClassName(match[1]);
}
//else check if selector is an id match
else if( selector.match(idexp) ){
//get id name and find element by it
var match = idexp.exec(selector);
this.el = document.getElementById(match[1]);
}
//else just search by tag
else{
this.el = document.getElementsByTagName(selector);
}
//attach easy html event to the element object
this.el.html = function(html){
//if html argument is undefined return innerHTML
if( typeof html == "undefined" ){
return $this.el.innerHTML;
}
//else update innerHTML
$this.el.innerHTML = html;
//return element object for method chaining
return $this.el
}
};
From my understanding, after the function is called, both $this and this refer to the selector parameter. If they're the same thing why do does the function need $this and why couldn't the html function be written:
this.el.html = function(html){
//if html argument is undefined return innerHTML
if( typeof html == "undefined" ){
return this.el.innerHTML;
}