0

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;
    }
Brian
  • 315
  • 3
  • 7
  • 12
  • 1
    What `this` refers to depends on **how** a function is called. Most likely the function `this.el.html` is called in such a way that `this` inside of it doesn't refer to the same values as `this` inside `$`. – Felix Kling Aug 22 '14 at 01:18
  • Please re-open this question. The suggested duplicate does not answer this question for this scenario. Refer to @FelixKling for the correct answer. – sahbeewah Aug 22 '14 at 01:28

0 Answers0