nazerke
7/19/2015 - 3:04 PM

Demonstrates both default and implicit binding. Also clarifies common confusion

Demonstrates both default and implicit binding. Also clarifies common confusion

<!DOCTYPE html>
<html>
  <head>
  <script>
  function foo(){
    var bar = "bar1";
    this.baz = baz;//"this" refers to global, because that's how foo was called 
                    //for, i.e. by default binding rule
    this.baz();  // therefore this line the same as if we called baz() outside 
                //the function
  }
  function baz(){
    console.log(this.bar);//"this" is still global, according to implicit binding
  }
  var bar = "bar2";
  foo();
</script>
  </head>
  <body>
    <!-- page content -->
  </body>
</html>